/**
 * Created by juyong.li on 2015/11/10.
 */
;
(function (window, angular) {
    'use strict';

    function isAllowI18n(scopeF) {
        // 判断当前页面是否允许国际化
        scopeF.multiLan = scopeF.$root.allowI18n
    }

    angular.module("YB.Widget", ['ngFileUpload'])
        .constant("MESG_TYPE", {
            Error: 0,
            Warn: 1,
            Success: 2,
            Note: 3,
            Ask: 4,
            Invalid: 5,
            NoAddress: 6
        })
        .service("ybWidget", ["$modal", "MESG_TYPE", "ybHttp", function ($modal, MESG_TYPE, ybHttp) {
            var fnShowConfirm = function (header, label, config) {
                var dft = {
                    header: "提示", // 弹框标题
                    message: "", // 弹框提示信息
                    label: "", // 输入框标题
                    maxLength: 200, // 输入框内容最大长度
                    required: true, // 输入框内容是否必填
                    isTextarea: true, // 是否是多行文本输入框

                    okName: "确定", // 确定按钮名称
                    cancelName: "取消", // 取消按钮名称
                };

                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    keyboard: false,
                    templateUrl: 'widget/modal/confirm.html',
                    controller: 'ConfirmCtrl',
                    resolve: {
                        settings: function () {
                            if (!angular.isArray(header) && angular.isObject(header)) { // header为对象
                                angular.extend(dft, header);
                            }

                            if (angular.isString(header)) { // header为字符串
                                angular.extend(dft, config);
                                if (!!header) {
                                    dft.header = header;
                                }
                                if (!!label) {
                                    if (angular.isArray(label)) {
                                        dft.contentList = label
                                    } else {
                                        dft.label = label;
                                    }
                                }
                            }

                            return dft;
                        }
                    }
                });
                return instance.result;
            };

            var fnShowMessage = function (content, type, config = {}) {
                var dft = {
                    Type: MESG_TYPE.Error,
                    Content: { message: "出错啦！" },
                    okName: "确定",
                    noName: "取消",
                };

                var instance = $modal.open({
                    size: config.size,
                    animation: false,
                    backdrop: "static",
                    keyboard: false,
                    templateUrl: 'widget/modal/message.html',
                    controller: 'MessageCtrl',
                    resolve: {
                        settings: function () {
                            angular.extend(dft, config);
                            if (!!content) {
                                if (angular.isString(content)) {
                                    dft.Content.message = content;
                                } else {
                                    dft.Content = content;
                                }
                            }
                            if (!!type) {
                                dft.Type = type;
                            }
                            return dft;
                        }
                    }
                });
                return instance.result;
            };

            var fnShowToaster = function (type, title, text) {
                var data = {
                    type: type,
                    title: title,
                    text: text
                };
                var instance = $modal.open({
                    templateUrl: 'widget/modal/toaster.html',
                    controller: 'ToasterCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnSetPicture = function (config) {
                var dft = {
                    Type: 7, //弹出框类型：1-local 2-net 3--space
                    Number: 1,
                    Force: true, // true 代表必须选择{{number}}个图片，false表示可以少于{{Number}}个图片
                    Size: 1 * 1024 * 1024, //默认图片最大为1M
                    FileType: ".jpeg,.png,.jpg" //默认的图片格式
                };

                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/picture.html',
                    controller: 'PictureCtrl',
                    resolve: {
                        settings: function () {
                            angular.extend(dft, config);
                            return dft;
                        }
                    }
                });
                return instance.result;

            };

            var fnShowLoginModal = function () {
                var instance = $modal.open({
                    animation: true,
                    templateUrl: 'widget/modal/login.html',
                    controller: 'LoginCtrl',
                    backdrop: "static",
                    keyboard: false
                });
                return instance.result;
            };

            var fnAuditMsg = function (config) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/audit.html',
                    controller: 'AuditMsgCtrl',
                    resolve: {
                        setting: function () {
                            return config;
                        }
                    }
                });
                return instance.result;
            };

            var fnBoxEditMsg = function (type) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/boxupEdit.html',
                    controller: 'BoxEditMsgCtrl',
                    resolve: {
                        setting: function () {
                            return type;
                        }
                    }
                });
                return instance.result;
            };

            var fnImportFile = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    keyboard: false,
                    templateUrl: 'widget/modal/importFile.html',
                    controller: 'ImportFileCtrl',
                    resolve: {
                        setting: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnFileUploader = function (item) {
                var dft = {
                    Type: 'upload', // upload view
                    maxFileCount: 10,
                    ImgSize: 5,
                    ImgTypes: "jpeg,png,jpg",
                    FileSize: 50,
                    FileTypes: "pdf",
                    urlRoot: 'device', // 图片上传接口的默认根路径（上传接口所在服务的路由名称）
                    urlType: 'ftp', // 图片默认根路径类型（取自ftp、oss、minio）
                    mnDir: '' // minio存储的目录
                };
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/fileUploader.html',
                    controller: 'FileUploaderCtrl',
                    resolve: {
                        settings: function () {
                            angular.extend(dft, item);
                            return dft;
                        }
                    }
                });
                return instance.result;
            };

            var fnViewImage = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    size: 'lg',
                    templateUrl: 'widget/modal/viewImage.html',
                    controller: 'ViewImageCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnSingleSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/singleSelector.html',
                    controller: 'SingleSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnDeliveryNoticeSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/deliveryNoticeSelector.html',
                    controller: 'DeliveryNoticeSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnAgentSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/agentSelector.html',
                    controller: 'AgentSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnWarehouseSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    size: 'lg',
                    templateUrl: 'widget/modal/warehouseSelector.html',
                    controller: 'WarehouseSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnWarehouseUsingSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/warehouseUsingSelector.html',
                    controller: 'WarehouseUsingSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };
            var fnWarehouseUsingUserSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/warehouseUsingSelector.html',
                    controller: 'WarehouseUsingUserSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };
            var fnDataSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    size: data.size || '',
                    templateUrl: 'widget/modal/dataSelector.html',
                    controller: 'DataSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnCodeSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/codeSelector.html',
                    controller: 'CodeSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnWarehouseASelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/warehouseSelector.html',
                    controller: 'WarehouseASelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnDatasShow = function (data) {
                var instance = $modal.open({
                    animation: false,
                    size: 'lg',
                    backdrop: "static",
                    templateUrl: 'widget/modal/datasShow.html',
                    controller: 'DatasShowCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnStorageReport = function (data) {
                var instance = $modal.open({
                    animation: false,
                    size: 'lg',
                    backdrop: "static",
                    templateUrl: 'widget/modal/storageReport.html',
                    controller: 'StorageReportCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnIntentionDetail = function (data) {
                var instance = $modal.open({
                    animation: false,
                    size: 'lg',
                    backdrop: "static",
                    templateUrl: 'widget/modal/intentionDetail.html',
                    controller: 'IntentionDetailCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnDeliveryDetail = function (data) {
                var instance = $modal.open({
                    animation: false,
                    size: 'lg',
                    backdrop: "static",
                    templateUrl: 'widget/modal/deliveryDetail.html',
                    controller: 'DeliveryDetailCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnDepotAreaSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/depotAreaSelector.html',
                    controller: 'DepotAreaSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnPriceSchemeSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/priceSchemeSelector.html',
                    controller: 'PriceSchemeSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnTransferFlagSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/transferFlagSelector.html',
                    controller: 'TransferFlagSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnDepotSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/depotSelector.html',
                    controller: 'DepotSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };
            var fnToSort = function (config, index) {
                for (var i = 0, len = config.length; i < len; i++) {
                    if (i != index) {
                        config[i].sortType = "";
                    }
                }
                if (config[index].sortType === "asc") {
                    config[index].sortType = "desc";
                } else {
                    config[index].sortType = "asc";
                }
                return config[index].sortType;
            };

            var fnGetDictionaryMap = function (type) {
                var typeIdMap = {
                    'deliveryWay': 'FYFS',
                    'payCondition': 'FKTJ',
                    'distributionChannel': 'FXQD',
                    'settleType': 'JSFS'
                };
                var param = {
                    parentCode: typeIdMap[type]
                };
                return ybHttp.Post('device', '/dataDictionary/searchList', param);
            };

            function fnGoBack() {
                window.history.go(-1);
            }

            function fnSetParentMainView(scope) {
                scope.$on('$destroy', function () {
                    showParentMainContent(true);
                });

                function showParentMainContent(isShow) {
                    scope.$emit("showListContent", isShow);
                }

                showParentMainContent(false);
            }

            // 参数说明：
            // printType：打印该类型单据的标识。
            //            printTemplateCtrl.js：定义该类型单据的打印模板标识；
            //            printData.js：使用此标识 定义打印模板初始信息对象的key；
            //            printTemplate.js：使用此标识 定义模板的TEMPLATE_CODE的可以 和 DEFAULT_TEMPLATE_FUN函数中 最终可使用的打印模板 对象的key。
            // cusInterface：自定义打印时获取数据的接口地址。
            //               打印时获取数据的接口默认配置在printData.js里。如果同一单据模板不同业务场景下 接口不同时，可用此参数设置。
            // billId：打印时获取数据的接口所需的参数为id或者billId时，可用此参数传参。
            //        （注：此参数是一个永远只有一个元素的数组，为历史设计者不合理的设计，待修改为字符串格式，因涉及页面过多暂未修改。）
            // cusParam：打印时获取数据的接口所需的参数不是id或者billId时，可用此对象参数。
            // recordPrint：当需要记录该单据的打印信息（是否打印，打印人，打印时间）时，可使用此对象参数。
            //             （注：此参数暂时设计为：仅有一个且key值固定是billNo的对象，后期可根据需要和后端配合扩展多个参数）
            // isBatchPrint：批量打印时，循环复用单行打印的数据。
            //               当后端接口返回的数据，仅仅是用list包装单行打印时使用的接口返回的数据时，可将此参数设为true。
            //               （注：当不是上述 循环复用单行打印数据 的批量打印时，忽略此参数。）
            // printDataInfo：业务页面提供数据，不再走上述调接口逻辑。
            //            （注：此参数类型为对象或者数组，若复用其他打印模板printType逻辑，数据类型和数据结构需和其保持一致）
            var fnIsPrintOrPreview = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/printOrPreview.html',
                    controller: 'PrintOrPreviewCtrl',
                    resolve: {
                        settings: function () {
                            angular.extend(data);
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnGuaranteesFeeSettleSelector = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/guaranteesFeeSettleSelector.html',
                    controller: 'GuaranteesFeeSettleSelectorCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnUpperFirstLetter = function (str) {
                return str.replace(/\b\w+\b/g, function (word) {
                    return word.substring(0, 1).toUpperCase() +
                        word.substring(1);
                });
            };

            // 获取小数点后有几位小数
            function getPoint(num) {
                var result;
                try {
                    result = num.toString().split(".")[1].length
                } catch (e) {
                    result = 0
                }
                return result;
            }

            // 多个数字之和，防止精度丢失
            function fnMultiPlus() {
                var args = arguments;
                if (args.length <= 0) {
                    return 0;
                }
                var _maxPoint = 0; // 小数最长的长度
                var _result = 0; // 最终的和
                var _curPoint; // 当前数字的小数点后有几位小数
                var _mi; // 10 多少次方
                for (var i = 0; i < args.length; i++) {
                    _curPoint = getPoint(args[i]);
                    _maxPoint = Math.max(_maxPoint, _curPoint);
                    _mi = Math.pow(10, _maxPoint);
                    _result = (Math.round(_result * _mi) + Math.round(args[i] * _mi)) / _mi;
                }
                return _result;
            }

            // 多个数字相减，防止数字精度丢失
            function fnMultiMinus() {
                var args = arguments;
                if (args.length <= 0) {
                    return 0;
                }
                if (args.length === 1) {
                    return args[0];
                }
                // 第一个值 依次 减去 后面的值
                var _maxPoint = getPoint(args[0]); // 小数最长的长度
                var _result = args[0]; // 最终的值
                var _curPoint; // 当前数字的小数点后有几位小数
                var _mi; // 10 多少次方
                for (var i = 1; i < args.length; i++) {
                    _curPoint = getPoint(args[i]);
                    _maxPoint = Math.max(_maxPoint, _curPoint);
                    _mi = Math.pow(10, _maxPoint);
                    _result = ((Math.round(_result * _mi) - Math.round(args[i] * _mi)) / _mi).toFixed(_maxPoint);
                }
                return _result;
            }

            function fnPlus(arg1, arg2) {
                var r1, r2, m;
                try {
                    r1 = arg1.toString().split(".")[1].length
                } catch (e) {
                    r1 = 0
                }
                try {
                    r2 = arg2.toString().split(".")[1].length
                } catch (e) {
                    r2 = 0
                }
                m = Math.pow(10, Math.max(r1, r2));
                return (arg1 * m + arg2 * m) / m
            }

            function fnMinus(val1, val2) {
                var r1, r2, m, n;
                try {
                    r1 = val1.toString().split(".")[1].length;
                } catch (e) {
                    r1 = 0
                }
                try {
                    r2 = val2.toString().split(".")[1].length;
                } catch (e) {
                    r2 = 0
                }
                m = Math.pow(10, Math.max(r1, r2));
                n = (r1 >= r2) ? r1 : r2;
                return ((val1 * m - val2 * m) / m).toFixed(n);
            }

            function fnTimes(arg1, arg2) {
                if (arg1 == "" || arg1 == undefined || arg2 == "" || arg2 == undefined) {
                    return "";
                }
                var m = 0,
                    s1 = arg1.toString(),
                    s2 = arg2.toString();
                try {
                    m += s1.split(".")[1].length
                } catch (e) {}
                try {
                    m += s2.split(".")[1].length
                } catch (e) {}
                return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
            }

            function fnDivide(arg1, arg2) {
                var t1 = 0,
                    t2 = 0,
                    r1, r2;
                try {
                    t1 = arg1.toString().split(".")[1].length
                } catch (e) {}
                try {
                    t2 = arg2.toString().split(".")[1].length
                } catch (e) {}
                r1 = Number(arg1.toString().replace(".", ""));
                r2 = Number(arg2.toString().replace(".", ""));
                return fnTimes((r1 / r2), Math.pow(10, t2 - t1));
            }

            function fnRemainder(arg1, arg2) {
                var t1 = 0,
                    t2;
                try {
                    t1 = fnDivide(arg1, arg2);
                } catch (e) {}
                t2 = t1.toString().split('.')[0];
                return fnMinus(arg1, fnTimes(t2, arg2));
            }

            function fnFormatStartDate(time) {
                return new Date(new Date(time).setHours(0, 0, 0, 0));
            }

            function fnFormatEndDate(time) {
                return new Date(new Date(time).setHours(23, 59, 59, 59));
            }

            function fnCheckDate(timeStart, timeEnd) {
                var timeObj = {
                    tStart: null,
                    tEnd: null
                };
                if ((angular.isUndefined(timeStart) || !timeStart) && (angular.isUndefined(timeEnd) || !timeEnd)) {
                    return timeObj;
                }
                if (!!timeStart && (angular.isUndefined(timeEnd) || !timeEnd)) {
                    timeObj.tStart = fnFormatStartDate(timeStart);
                    return timeObj;
                }
                if ((angular.isUndefined(timeStart) || !timeStart) && !!timeEnd) {
                    timeObj.tEnd = fnFormatEndDate(timeEnd);
                    return timeObj;
                }
                var tmpTime = timeStart;
                if (timeEnd < timeStart) {
                    timeObj.tStart = fnFormatStartDate(timeEnd);
                    timeObj.tEnd = fnFormatEndDate(tmpTime);
                } else {
                    timeObj.tStart = fnFormatStartDate(timeStart);
                    timeObj.tEnd = fnFormatEndDate(timeEnd);
                }
                return timeObj;
            }

            function fnGetTableCol(tableCols, dataField) {
                for (var i = 0; i < tableCols.length; i++) {
                    if (tableCols[i].dataField === dataField) {
                        return tableCols[i];
                    }
                }
                return {};
            }

            function fnHideTableCols(tableCols, hideItemCols) {
                return tableCols.filter(ttf => !hideItemCols.includes(ttf.dataField));
            }

            var fnSelectDeliveryAddress = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/selectDeliveryAddress.html',
                    controller: 'SelectDeliveryAddressCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnDeleteShelf = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    keyboard: false,
                    templateUrl: 'widget/modal/deleteShelf.html',
                    controller: 'DeleteShelfCtrl',
                    resolve: {
                        setting: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnScissorPicture = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    size: 'lg',
                    keyboard: false,
                    templateUrl: 'widget/modal/scissorPicture.html',
                    controller: 'ScissorPictureCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnShowDatePicker = function (data) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/myDatePicker.html',
                    controller: 'ShowDatePickerCtrl',
                    resolve: {
                        setting: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            var fnLogisticsWaybillDetail = function (data) {
                var instance = $modal.open({
                    animation: false,
                    size: 'lg',
                    backdrop: "static",
                    templateUrl: 'widget/modal/logisticsWaybillDetail.html',
                    controller: 'LogisticsWaybillDetailCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };

            // add by spd
            var fnSellIntentionDetail = function (data) {
                var instance = $modal.open({
                    animation: false,
                    size: 'lg',
                    backdrop: "static",
                    templateUrl: 'widget/modal/sellIntentionDetail.html',
                    controller: 'SellIntentionDetailCtrl',
                    resolve: {
                        settings: function () {
                            return data;
                        }
                    }
                });
                return instance.result;
            };
            //end

            var fnAutoAddHandoverBill = function (config) {
                var instance = $modal.open({
                    animation: false,
                    backdrop: "static",
                    templateUrl: 'widget/modal/autoAddHandoverBill.html',
                    controller: 'AutoAddHandoverBillCtrl',
                    resolve: {
                        settings: function () {
                            return config;
                        }
                    }
                });
                return instance.result;
            };

            /**
             * @param {Object} file 文件对象
             * url 文件下载地址
             * name 文件名称
             */
            var fnDonwloadFileByBlob = function (file) {
              const xhr = new XMLHttpRequest();
              xhr.open('GET', file.url, true);
              xhr.responseType = 'blob';
              xhr.onload = function () {
                if (xhr.status === 200) {
                  const res = xhr.response;
                  const link = document.createElement('a');
                  link.style.display = 'none';
                  const url = window.URL.createObjectURL(res);
                  link.href = url;
                  if (file.name) {
                      link.setAttribute('download', file.name);
                  }
                  document.body.appendChild(link);
                  link.click();
                  window.URL.revokeObjectURL(link.href);
                  document.body.removeChild(link);
                }
              }
              xhr.send()
            };

            var fnSelGaodeMap = function (config) {
                var instance = $modal.open({
                  animation: false,
                  backdrop: "static",
                  templateUrl: "widget/modal/selGaodeMap.html",
                  controller: "SelGaodeMapCtrl",
                  resolve: {
                    settings: function () {
                      return config || {};
                    },
                  },
                });
                return instance.result;
            };
      
            var fnShowGaodeMapRoute = function (config) {
                var instance = $modal.open({
                  animation: false,
                  size: "lg",
                  backdrop: "static",
                  templateUrl: "widget/modal/showGaodeMapRoute.html",
                  controller: "ShowGaodeMapRouteCtrl",
                  resolve: {
                    settings: function () {
                      return config || {};
                    },
                  },
                });
                return instance.result;
            };
      
            var fnRepairForm = function (config) {
                var instance = $modal.open({
                  allowPropagation: true,
                  animation: false,
                  size: "md",
                  backdrop: "static",
                  templateUrl: "widget/modal/repairForm.html",
                  controller: "RepairFormCtrl",
                  resolve: {
                    settings: function () {
                      return config;
                    },
                  },
                });
                return instance.result;
            };

            // 图片上传时使用lib/ckeditor/plugins/image/dialogs/image.js
            window.ybWidget = window.ybWidget || {};
            window.ybWidget.SetPicture = fnSetPicture;

            return {
                DeleteShelf: fnDeleteShelf,
                ShowConfirm: fnShowConfirm,
                ShowMessage: fnShowMessage,
                ShowToaster: fnShowToaster,
                SetPicture: fnSetPicture,
                ShowLoginModal: fnShowLoginModal,
                AuditMsg: fnAuditMsg,
                BoxEditMsg: fnBoxEditMsg,
                ImportFile: fnImportFile,
                FileUploader: fnFileUploader,
                ViewImage: fnViewImage,
                SingleSelector: fnSingleSelector,
                WarehouseSelector: fnWarehouseSelector,
                WarehouseUsingSelector: fnWarehouseUsingSelector,
                WarehouseUsingUserSelector: fnWarehouseUsingUserSelector,
                DataSelector: fnDataSelector,
                CodeSelector: fnCodeSelector,
                WarehouseASelector: fnWarehouseASelector,
                DepotAreaSelector: fnDepotAreaSelector,
                AgentSelector: fnAgentSelector,
                ToSort: fnToSort,
                GetDictionaryMap: fnGetDictionaryMap,
                SetParentMainView: fnSetParentMainView,
                GoBack: fnGoBack,
                UpperFirstLetter: fnUpperFirstLetter,
                SetIsPrintOrPreview: fnIsPrintOrPreview,
                PriceSchemeSelector: fnPriceSchemeSelector,
                TransferFlagSelector: fnTransferFlagSelector,
                DepotSelector: fnDepotSelector,
                Plus: fnPlus,
                MultiPlus: fnMultiPlus,
                MultiMinus: fnMultiMinus,
                Minus: fnMinus,
                Times: fnTimes,
                Divide: fnDivide,
                Remainder: fnRemainder,
                FormatStartDate: fnFormatStartDate,
                FormatEndDate: fnFormatEndDate,
                CheckDate: fnCheckDate,
                GetTableCol: fnGetTableCol,
                HideTableCols: fnHideTableCols,
                DeliveryNoteSelector: fnDeliveryNoticeSelector,
                DatasShow: fnDatasShow,
                StorageReport: fnStorageReport,
                IntentionDetail: fnIntentionDetail,
                DeliveryDetail: fnDeliveryDetail,
                SelectDeliveryAddress: fnSelectDeliveryAddress,
                ScissorPicture: fnScissorPicture,
                ShowDatePicker: fnShowDatePicker,
                LogisticsWaybillDetail: fnLogisticsWaybillDetail,
                AutoAddHandoverBill: fnAutoAddHandoverBill,
                GuaranteesFeeSettleSelector: fnGuaranteesFeeSettleSelector,
                SellIntentionDetail: fnSellIntentionDetail, //add by spd
                DonwloadFileByBlob: fnDonwloadFileByBlob,
                SelwGaodeMap: fnSelGaodeMap,
                ShowGaodeMapRoute: fnShowGaodeMapRoute,
                RepairForm: fnRepairForm,
            };
        }])
        .controller("MessageCtrl", ['$scope', '$modalInstance', 'settings', 'MESG_TYPE', function ($scope, $modalInstance, settings, MESG_TYPE) {
            isAllowI18n($scope);

            $scope.Type = MESG_TYPE;
            $scope.settings = settings;

            $scope.ok = function () {
                $modalInstance.close("ok");
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };

        }])

        .controller("ToasterCtrl", ['$translate', '$scope', 'settings', 'toaster', '$modalInstance', '$timeout', function ($translate, $scope, settings, toaster, $modalInstance, $timeout) {
            toaster.pop({
                type: settings.type,
                title: $translate.instant(settings.title || ''),
                body: settings.text,
                showCloseButton: false,
                timeout: 2000
            });

            $timeout(function () {
                $modalInstance.close();
            });
        }])

        .controller("ConfirmCtrl", ['$scope', '$modalInstance', 'settings', function ($scope, $modalInstance, settings) {
            $scope.settings = settings;
            $scope.confirmInfo = {};
            $scope.submitted = false;

            $scope.ok = function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.confirmInfo.contentVal) {
                    $scope.confirmInfo.contentVal = $scope.confirmInfo.contentVal.trim();
                }
                $modalInstance.close($scope.confirmInfo.contentVal || $scope.settings.contentList);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("PrintOrPreviewCtrl", ['$scope', '$modalInstance', 'settings', 'ybWidget', 'ybHttp', 'dolphinPrintServer', "$controller", "UserContextService", "$timeout", "TEMPLATE_CODE",
            function ($scope, $modalInstance, settings, ybWidget, ybHttp, dolphinPrintServer, $controller, UserContextService, $timeout, TEMPLATE_CODE) {
                isAllowI18n($scope);

                var param = settings;
                var preventRepeatPrint = false;
                $scope.TemplateLists = [];

                function getPrintTemplates() {
                    var params = {
                        CurPage: 1,
                        PageSize: 0,
                        TemplateType: TEMPLATE_CODE[param.printType]
                    };
                    ybHttp.Get("device", "/printTemplate/list", params).then(function (data) {
                        if (data.code !== 0) {
                            ybWidget.ShowMessage(data);
                            return;
                        }
                        angular.forEach(data.value, function (item) {
                            for (var key in item) {
                                item[ybWidget.UpperFirstLetter(key)] = item[key];
                            }
                        });
                        $scope.TemplateLists = data.value;
                        if ($scope.TemplateLists.length == 0) {
                            $scope.TemplateLists = [{
                                TemplateName: "系统模板",
                                Id: "0000"
                            }];
                            $scope.selectedTemplate = $scope.TemplateLists[0];
                            return;
                        }
                        for (var i = 0; i < $scope.TemplateLists.length; i++) {
                            if ($scope.TemplateLists[i].IsDefault) {
                                $scope.selectedTemplate = $scope.TemplateLists[i];
                                return;
                            }
                        }
                    });
                }

                // 打印
                $scope.printStart = function () {
                    if (preventRepeatPrint) return;
                    preventRepeatPrint = true;
                    param.type = "print";
                    sendMsg();
                };

                // 预览
                $scope.previewStart = function () {
                    param.type = "preview";
                    sendMsg();
                };

                function sendMsg() {
                    if (!$scope.selectedTemplate) {
                        ybWidget.ShowToaster("error", "请选择打印模板");
                        return;
                    }
                    localStorage.setItem("S_Templates", JSON.stringify($scope.selectedTemplate));
                    param.template = $scope.selectedTemplate;
                    $timeout(function () {
                        printByLodopServer(param);

                        /* if (param.recordPrint) {
                            // 需要记录是否打印
                            ybHttp.Post("device", "/printTemplate/printRecord", param.recordPrint).then(function(data) {
                                if (data.code !== 0) {
                                    ybWidget.ShowMessage(data || '记录是否打印失败');
                                }
                                $modalInstance.close();
                            })
                        } else {
                            $modalInstance.close();
                        } */
                        $modalInstance.close();
                    }, 10);
                }

                function printByLodopServer(param) {
                    return dolphinPrintServer.getHTMLPrintTemplates($scope, param).then(function (list) {
                        var params = {
                            type: param.type,
                            printType: param.printType,
                            tempaltePrintPaper: angular.fromJson(param.template.PageSetting),
                            isPrintLine: param.template.IsPrintLine,
                            list: list,
                        };
                        $controller("LodopServiceCtrl").LodopPrintOrPreview(params)

                    }, function (error) {
                        console.info(error);
                    });
                }

                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };

                (function () {
                    getPrintTemplates();
                })();
            }
        ])
        .controller("PictureCtrl", ['$scope', '$modalInstance', '$q', 'Upload', '$log', 'settings', 'ybConfig', "ybWidget", "ybNavigator",
            function ($scope, $modalInstance, $q, Upload, $log, settings, ybConfig, ybWidget, ybNavigator) {
                $scope.pictureFile = settings;
                $scope.remindMessage = "温馨提示，图片格式" + $scope.pictureFile.FileType.replace(/,/g, '、') + ", 大小限制" + Math.ceil(settings.Size / (1024 * 1024)) + "M" + "，请选择" + settings.Number + "张图片上传";
                $scope.isSelected = false;
                var isIE8 = ybNavigator.IsIE8();

                var uploadFiles = function (files) {
                    var uploadList = [];
                    var upload;
                    for (var i = 0; i < files.length; ++i) {
                        upload = Upload.upload({
                            url: ybConfig.getConfig().baseUrl.Site + ybConfig.getConfig().serviceName.device + settings.upLoadImgUrl,
                            data: {
                                file: files[i].Url,
                                imgFile: files[i].Url
                            }
                        });
                        uploadList.push(upload);
                    }
                    var allUplaod = $q.all(uploadList);
                    allUplaod.then(function (resp) {
                            return resp;
                        },
                        function (resp) {
                            ybWidget.ShowToaster("error", "", "图片上传失败");
                            return resp;
                        }
                    );
                    return allUplaod;
                };

                $scope.ok = function () {
                    var files = [];
                    var data = [];
                    if (isIE8) {
                        if (settings.Number == 1 && $scope.selected.items.length == 1) {
                            $modalInstance.close($scope.selected.items[0]);
                            return;
                        }
                        $modalInstance.close($scope.selected.items);
                        return;
                    }

                    for (var i = 0; i < $scope.selected.items.length; ++i) {
                        if ($scope.selected.items[i].Type != "Local") { //非本地文件，不需要上传
                            data.push({
                                Url: $scope.selected.items[i].Url,
                                Type: $scope.selected.items[i].Type
                            });
                            continue;
                        }
                        files.push($scope.selected.items[i]);
                    }
                    var allUplaod = uploadFiles(files);
                    allUplaod.then(function (resp) {
                        for (var i = 0; i < resp.length; ++i) {
                            data.push({
                                Url: resp[i].data.value.imageUrl || resp[i].data.value,
                                Name: resp[i].config.data.file.name,
                                Type: "Local"
                            });
                        }
                        if (settings.Number == 1 && $scope.selected.items.length == 1) {
                            $modalInstance.close(data[0]);
                            return;
                        }
                        $modalInstance.close(data);
                    });
                };

                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };

                $scope.selected = {
                    items: []
                };
                $scope.selectItem = function (item) {
                    if ($scope.selected.items.length >= settings.Number) {
                        var temp = $scope.selected.items.shift();
                        $scope.$broadcast(temp.Type, temp.Index);
                    }
                    $scope.selected.items.push(item);
                };
                $scope.unselectItem = function (item) {
                    var i = 0;
                    for (i = 0; i < $scope.selected.items.length; ++i) {
                        if ($scope.selected.items[i].Type == item.Type && $scope.selected.items[i].Index == item.Index) {
                            $scope.selected.items.splice(i, 1);
                            break;
                        }
                    }
                };
                $scope.uploadFiles = uploadFiles;

            }
        ])
        .controller("PicLocalCtrl", ['$scope', '$timeout', "ybWidget", "ybNavigator", function ($scope, $timeout, ybWidget, ybNavigator) {
            $scope.items = [];
            $scope.files = [];
            var prevFiles = [];
            $scope.isIE8 = ybNavigator.IsIE8();

            ybNavigator.ShowFlashHint();

            $scope.$on("Local", function (event, index) {
                $scope.items[index].Selected = false;
            });
            $scope.select = function (index) {
                var selected = !$scope.items[index].Selected;
                var item = {
                    Url: $scope.items[index].Url,
                    Type: "Local",
                    Index: index
                };
                $scope.items[index].Selected = selected;
                if (selected) {
                    $scope.selectItem(item);
                } else {
                    $scope.unselectItem(item);
                }
            };

            var preview = function () {
                var files = [];
                if ($scope.files == null || $scope.files.length == 0) {
                    return;
                }

                //解决IE8上传两次的问题
                if ($scope.isIE8 && (prevFiles.length > 0) && (prevFiles[0].id == $scope.files[0].id)) {
                    prevFiles = [];
                    return;
                }
                prevFiles = angular.copy($scope.files);

                for (var i = 0; i < $scope.files.length; ++i) {
                    var item = {
                        Url: $scope.files[i]
                    };
                    if ($scope.isIE8) {
                        files.push(item);
                    } else {
                        setPreviewItems(item);
                    }
                }
                if ($scope.isIE8) {
                    $scope.uploadFiles(files).then(function (resp) {
                        for (var i = 0; i < resp.length; ++i) {
                            var item = {
                                Url: resp[i].data.Value.Key
                            };
                            setPreviewItems(item);
                        }
                    });
                }
            };

            function setPreviewItems(item) {
                $scope.files.length = 0;
                angular.extend(item, {
                    Selected: true,
                    Type: "Local",
                    Index: $scope.items.length
                });
                $scope.items.push(item);
                $scope.selectItem(item);
            }

            $scope.checkFileValidate = function (file) {
                if (file.type.indexOf("image") == -1) {
                    ybWidget.ShowToaster("error", "提示", "文件格式错误，请选择图片");
                    return false;
                }
                var index = file.type.indexOf("/");
                var typeName = file.type.substring(index + 1);
                if ($scope.pictureFile.FileType.indexOf(typeName) == -1) {
                    ybWidget.ShowToaster("error", "提示", "图片格式错误，请重新选择");
                    return false;
                }
                if (file.size > $scope.pictureFile.Size) {
                    ybWidget.ShowToaster("error", "提示", "图片大小超过了" + Math.ceil($scope.pictureFile.Size / (1024 * 1024)) + "M");
                    return false;
                }
                return true;
            };
            $scope.preview = preview;

        }])

        .controller("LoginCtrl", ['$scope', '$modalInstance', '$window', 'UserContextService', 'ybConfig', 'ybHttp', 'ybWidget', 'MESG_TYPE', '$filter', '$timeout', function ($scope, $modalInstance, $window, UserContextService, ybConfig, ybHttp, ybWidget, MESG_TYPE, $filter, $timeout) {
            isAllowI18n($scope);

            $scope.user = {
                loginName: "",
                password: "",
                code: ""
            };
            $scope.failLogin = false;
            $scope.submitted = false;
            $scope.codeImg = '';
            var authId = '';

            function getAuthCode() {
                var service = "auth";
                var reqUrl = "/auth/authInfo";
                ybHttp.Get(service, reqUrl).then(function (data) {
                    if (data.code != 0) {
                        ybWidget.ShowMessage(data.message);
                        return;
                    }
                    authId = data.value.authId;
                    $scope.codeImg = window.AppData.config.serviceName.auth + '/auth/kaptcha?authid=' + data.value.authId;
                })
            }

            $scope.refresh = function () {
                getAuthCode();
            };

            function getLoginIpInfo() {
                ybHttp.Get("device", "/logininfo/abnormalLogin").then(function (data) {
                    if (data.value) {
                        var loginDate = $filter("YbDate")(data.value.loginDate, 'yyyy-MM-dd HH:mm:ss');
                        var loginIp = data.value.loginIp || '';
                        var loginIpHome = data.value.ipHome || '';

                        var msg = "系统检测到您本次登录的ip信息与上次不同。<div class='abnormal-msg'><span>上次登录信息：</span>登录时间：" + loginDate + '<br/>登录ip：' + loginIp + '<br/>ip归属地：' + loginIpHome + '</div>'
                        var okName = '确定'
                        if (localStorage.getItem('lang') == 'en-US') {
                            msg = "The system detects that the ip information you log in this time is different from the last time。<div class='abnormal-msg'><span>Last login info：</span>Login time：" + loginDate + '<br/>Login ip：' + loginIp + '<br/>Ip attribution：' + loginIpHome + '</div>'
                            okName = 'Confirm'
                        } else if (localStorage.getItem('lang') == 'es-ES') {
                            msg = "El sistema ha detectado que su información ip para este inicio de sesión es diferente de la última vez。<div class='abnormal-msg'><span>Última información de acceso：</span>Hora de inicio：" + loginDate + '<br/>Iniciar sesión ip：' + loginIp + '<br/>Lugar de propiedad ip：' + loginIpHome + '</div>'
                            okName = 'Determinar'
                        } else if (localStorage.getItem('lang') == 'in') {
                            msg = "Sistem mendeteksi ip informasi-mu untuk masuk berbeda dari terakhir kali。<div class='abnormal-msg'><span>Informasi login terakhir：</span>Log masuk waktu：" + loginDate + '<br/>Masuk ip：' + loginIp + '<br/>Ip milik：' + loginIpHome + '</div>'
                            okName = 'yakin'
                        } else if (localStorage.getItem('lang') == 'ru') {
                            msg = "Система обнаружила, что ip-сообщение, которое вы залогинились на этот раз, отличается от предыдущего。<div class='abnormal-msg'><span>Последний логин：</span>Время входа：" + loginDate + '<br/>Логин：' + loginIp + '<br/>Ip-адрес：' + loginIpHome + '</div>'
                            okName = 'увер'
                        }

                        ybWidget.ShowMessage(msg, MESG_TYPE.Warn, {isHtml: true}, okName).then(function () {
                            reloadInfo();
                        });
                    } else {
                        reloadInfo();
                    }
                });
            }

            function reloadInfo() {
                UserContextService.GetAuthCodes();
                UserContextService.GetSelfCompanyInfo().then(() => {
                    UserContextService.GetUserInfo();
                });
            }

            $scope.login = function (isvalid) {
                if (!isvalid) {
                    $scope.submitted = true;
                    return;
                }
                $scope.submitted = false;
                $scope.user.authId = authId;
                var result = UserContextService.Login($scope.user);
                result.then(function (data) {
                    $scope.failLogin = false;
                    $modalInstance.close(data);
                    getLoginIpInfo();
                },
                function (data) {
                    $scope.failLogin = true;
                    $scope.Message = data;
                    $scope.user.Password = "";
                    $scope.user.ValidateCode = "";
                    $scope.refresh();
                });
            };

            $scope.cancel = function () {
                $modalInstance.dismiss("cancel");
                $window.location.href = ybConfig.getConfig().baseUrl.LoginSite;
            };

            (function () {
                getAuthCode();
            })();
        }])

        .controller("AuditMsgCtrl", ['$scope', '$modalInstance', 'setting', 'ybWidget', 'MESG_TYPE', function ($scope, $modalInstance, setting, ybWidget, MESG_TYPE) {
            $scope.modalTitle = setting.title || '审核';
            $scope.modalNoAuditMsg = setting.noAuditMsg; // 无需审核意见

            $scope.auditRemark = "";
            $scope.auditConditon = {
                isAbnormal: 0
            };

            $scope.selectReconciliate = function () {
                ybWidget.DataSelector({
                    title: '对账人',
                    url: '/employee/list',
                    isNotFilterParam: false,
                    keyWords: [{label: '姓名', field: 'cnameLike'}],
                    fields: [
                        {
                            name: '姓名',
                            dataField: 'cname',
                            width: "100%"
                        }
                    ]
                }).then(function (data) {
                    $scope.auditConditon.reconciliateName = data.cname;
                    $scope.auditConditon.reconciliateId = data.id;
                })
            };

            $scope.ok = function () {
                let preValidateRes = true; // 点击操作按钮(同意、拒绝)之前的预校验标识，false 表示校验失败。
                if (setting.validateCb) {
                    preValidateRes = setting.validateCb($scope.auditRemark, $scope.auditConditon);
                }
                if (!preValidateRes) return;

                if (setting.passCb) {
                    setting.passCb($scope.auditRemark, $scope.auditConditon).then(function() {
                        $modalInstance.close();
                    }).catch(() => {})
                } else {
                    $modalInstance.close($scope.auditRemark, $scope.auditConditon);
                }
            };
            $scope.refuse = function () {
                let preValidateRes = true; // 点击操作按钮(同意、拒绝)之前的预校验标识，false 表示校验失败。
                if (setting.validateCb) {
                    preValidateRes = setting.validateCb($scope.auditRemark, $scope.auditConditon);
                }
                if (!preValidateRes) return;

                if(!setting.validateCb && !$scope.modalNoAuditMsg && $scope.auditRemark == ''){
                    ybWidget.ShowMessage(`请输入${$scope.modalTitle}意见`, MESG_TYPE.Error);
                    return;
                }

                if (setting.refuseCb) {
                    setting.refuseCb($scope.auditRemark, $scope.auditConditon).then(function() {
                        $modalInstance.close();
                    })
                } else {
                    $modalInstance.close($scope.auditRemark, $scope.auditConditon);
                }
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("TransferFlagSelectorCtrl", ['$scope', '$modalInstance', 'settings', 'ybWidget', 'MESG_TYPE', function ($scope, $modalInstance, settings, ybWidget, MESG_TYPE) {
            $scope.transferFlag = 1;
            $scope.modalTitle = "test";
            $scope.transferList = [{
                code: 0,
                name: "不接受"
            },{
                code: 1,
                name: "接受"
            }];

            $scope.ok = function () {
                $modalInstance.close($scope.transferFlag);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("BoxEditMsgCtrl", ['$scope', '$modalInstance', 'setting', function ($scope, $modalInstance, setting) {
            $scope.info = setting;
            $scope.ok = function () {

                $modalInstance.close($scope.info);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("DeleteShelfCtrl", ['$scope', '$modalInstance', 'setting', 'ybWidget', 'ybHttp', function ($scope, $modalInstance, setting, ybWidget, ybHttp) {

            isAllowI18n($scope);

            $scope.shelfInfo = angular.copy(setting);
            $scope.submitted = false;
            $scope.errMessage = '';

            $scope.ok = function (valid) {
                $scope.errMessage = '';
                if (!valid) {
                    $scope.submitted = true;
                    return false;
                }
                var reqUrl = '/warehouse/delLocations';
                var param = angular.copy($scope.shelfInfo);
                ybHttp.Post('device', reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        $scope.errMessage = resp.message || '删除失败，请重新操作';
                        $scope.submitted = true;
                        return;
                    }
                    $modalInstance.close('success');
                    ybWidget.ShowToaster('success', '操作成功');
                });
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("ImportFileCtrl", ['$scope', '$modalInstance', 'setting', 'Upload', 'ybHttp', 'ybWidget', 'ybNavigator', 'EventBus', 'MESG_TYPE', function ($scope, $modalInstance, setting, Upload, ybHttp, ybWidget, ybNavigator, EventBus, MESG_TYPE) {
            isAllowI18n($scope);
            $scope.types = setting.types;
            $scope.modalName = setting.name;
            $scope.modalTitle = "导入" + setting.name;
            $scope.hideTemplate = setting.hideTemplate;
            $scope.templateReqUrl = ybHttp.RequestUrl(setting.templateReqService, setting.templateReqUrl);
            $scope.downloadMethod = setting.downloadMethod;
            $scope.condition = setting.templateCondition || {}

            $scope.isloading = false;

            $scope.fileErrMsg = "";
            $scope.importErrMsg = "";
            $scope.importErrList = [];
            $scope.importSuccList = [];
            $scope.partSucc = false;

            ybNavigator.ShowFlashHint();

            $scope.clearErrorMsg = function () {
                $scope.fileErrMsg = "";
                $scope.importErrMsg = "";
                $scope.importErrList = [];
                $scope.importSuccList = [];
                $scope.partSucc = false;
            };

            $scope.importFile = function (file) {
                if (!file) {
                    $scope.fileErrMsg = "请先上传文件";
                    return;
                }

                var reg;
                var fileErrMsgStr;
                if ($scope.types && $scope.types.length > 0) { // 自定义支持的文件类型
                    var regStr = "\\.(";
                    var fileTypeStr = "";
                    angular.forEach($scope.types, function (item, idx) {
                        var itemLower = item.toLowerCase();
                        var itemUpper = item.toUpperCase();
                        regStr += (idx == 0 ? '' : '|') + itemLower;
                        regStr += "|" + itemUpper;
                        fileTypeStr += (idx == 0 ? '.' : '、.') + itemLower;
                    })
                    regStr += ")$";
                    reg = new RegExp(regStr);
                    fileErrMsgStr = "请选择整理好的 " + fileTypeStr + " 格式文件";
                } else if (setting.isImage) {
                    reg = /\.(png|PNG|jpeg|JPEG|gif|GIF|bmp|BMP|jpg|JPG)$/;
                    fileErrMsgStr = "请选择整理好的图片格式文件(支持：png、jpeg、gif、bmp、jpg)";
                } else {
                    reg = /\.(xls|XLS|xlsx|XLSX)$/;
                    fileErrMsgStr = "请选择整理好的.xls或.xlsx格式文件";
                }


                if (!setting.ignoreFormat && !reg.test(file.name)) {
                    $scope.fileErrMsg = fileErrMsgStr;
                    return;
                }

                const maxImgSizeTemp = angular.isUndefined(setting.maxImgSize) ? 1 : setting.maxImgSize;
                if (setting.isImage && file.size > maxImgSizeTemp * 1024 * 1024) {
                    $scope.fileErrMsg = `请上传${maxImgSizeTemp}M以内的图片`;
                    return;
                }

                $scope.isloading = true;

                var service = setting.importReqService;
                var reqUrl = setting.importReqUrl;
                file.upload = Upload.upload({
                    url: ybHttp.RequestUrl(service, reqUrl),
                    method: 'POST',
                    data: {
                        key: file.name,
                        'Content-Type': file.type === null || file.type === '' ? 'application/octet-stream' : file.type,
                        "x-orgId": setting.orgId,
                        "x-warehouseCode": setting.warehouseCode,
                        "x-areaCode": setting.areaCode,
                        "x-dealerOrgId": setting.dealerOrgId,
                        "x-billId": setting.billId,
                        "x-isDirectCast": setting.isDirectCast,
                        "x-materialsId": setting.materialsId,
                        "x-soldOrgId": setting.soldOrgId,
                        "x-ratingId": setting.ratingId,
                        "x-supplierCode": setting.supplierCode,
                        "x-targetOrgId": setting.targetOrgId || '',
                        "x-saleId": setting.saleId,
                        "x-jckPriceFlag": setting.jckPriceFlag,
                        filename: file.name,
                        file: file,
                        ...setting.otherParams
                    }
                }).success(function (resp, status, headers, config) {
                    $scope.isloading = false;
                    fnImportData(resp);

                }).error(function (data, status, headers, config) {
                    $scope.isloading = false;
                });
            };

            function fnImportData(resp) {
                if (resp.code !== 0) {
                    if (resp.code == 21) {
                        // 部分导入成功的公共处理
                        // 导入零件、导入产品组和零件用途的在响应码为0的逻辑里处理

                        $scope.partSucc = true;
                        $scope.importSuccList = resp.value.successList;
                        ybWidget.ShowToaster("success", "部分导入成功");
                        handleErrorList(resp.value.errorList);
                        return;
                    }

                    // 全部导入失败
                    ybWidget.ShowToaster("error", "导入失败");
                    if (!resp.value) {
                        $scope.importErrMsg = resp.message;
                    } else if (typeof (resp.value) === "string") {
                        $scope.importErrMsg = resp.value;
                    } else {
                        handleErrorList(resp.value.errorList || resp.value);
                    }
                    return;
                }

                const tempUrls = ['/materials/import', '/materials/importPorductGroupExcel'];
                if (tempUrls.includes(setting.importReqUrl)) {
                    if (resp.value && resp.value.length > 0) {
                        // 导入零件、导入产品组和零件用途 （处理部分导入成功）
                        $scope.partSucc = true;
                        ybWidget.ShowToaster("success", "部分导入成功");
                        handleErrorList(resp.value);
                        return;
                    }
                }

                // 全部导入成功
                ybWidget.ShowToaster("success", "操作成功");
                $modalInstance.close(resp.value ? (resp.value.successList || resp.value) : '');
            }

            function handleErrorList(errDatas) {
                errDatas.forEach(e => {
                    e.errRow = e.errorRow || e.index;
                    e.errMessage = e.remark || e.remarks || e.errMsg;
                })
                $scope.importErrList = errDatas;
            }

            $scope.cancel = function () {
                if (!!$scope.isloading) {
                    return;
                }

                if ($scope.partSucc) {
                    $modalInstance.close($scope.importSuccList);
                } else {
                    if ($scope.importErrList.length > 0) {
                        $modalInstance.dismiss('error');
                    }
                    $modalInstance.dismiss('cancel');
                }
            };
        }])

        .controller("FileUploaderCtrl", ['$scope', '$modalInstance', 'settings', 'Upload', 'ybHttp', '$http', 'ybConfig', 'ybWidget', 'ybNavigator', 'UserContextService', 'MESG_TYPE', function ($scope, $modalInstance, settings, Upload, ybHttp, $http, ybConfig, ybWidget, ybNavigator, UserContextService, MESG_TYPE) {
            const imgRootObj = {
                'ftp': ybConfig.getConfig().baseUrl.BjxlshFtp,
                'oss': ybConfig.getConfig().baseUrl.ImgOssUrl,
                'minio': ybConfig.getConfig().baseUrl.ImgMinioUrl + settings.mnDir,
            }
            const imgUploadUrlObj = {
                'ftp': '/ftp/uploadFile',
                'oss': '/obs/uploadImg',
                'minio': '/minio/uploadImage',
            }

            $scope.ImgTypes = settings.ImgTypes; // 允许的图片类型
            $scope.ImgSize = settings.ImgSize // 单张图片大小

            $scope.FileTypes = settings.FileTypes; // 允许的文档类型
            $scope.FileSize = settings.FileSize; // 单个文档大小

            $scope.ignoreFileFormat = settings.ignoreFormat; // 是否不校验文件格式

            $scope.canUpload = settings.Type == 'upload'; // 是否可以上传

            $scope.maxFileCount = settings.maxFileCount; // 允许上传的文件数量
            
            $scope.fileList = []; // 文件列表

            if ("fileList" in settings) {
              angular.forEach(settings.fileList, function (item) {
                if (!item.hasUpload) {
                  return;
                }
                item.fileUrlShow = getImgUrlShow(item.fileUrl);
                if (!("isImg" in item)) {
                    // 根据文件名判断已经上传过的文件是否是图片（无法根据文件的type判断）
                    let isImgTemp = false;
                    if (item.name) {
                        const [_, fileType] = item.name.split(".");
                        isImgTemp = 'png|PNG|jpeg|JPEG|gif|GIF|bmp|BMP|jpg|JPG|jfif'.includes(fileType);
                    }
                    item.isImg = isImgTemp;

                    if (item.isImg) {
                        item.imgUrlShow = item.fileUrlShow;
                    }
                }
              })

              $scope.fileList = settings.fileList || [];
            }

            $scope.handleFileSelect = function (files) {
                var errMsgStr = "";
                angular.forEach(files, function(file){
                    const isFileImg = file.type.startsWith('image/');
                    file.isImg = isFileImg; // 标记是否为图片

                    // 判断文件格式
                    const [_, fileType] = file.name.split(".");
                    if (!$scope.ignoreFileFormat && !$scope.ImgTypes.includes(fileType) && !$scope.FileTypes.includes(fileType)) {
                        errMsgStr += file.name + " 文件格式错误<br/>";
                        file.isValidateError = true;
                        return;
                    }

                    // 判断文件大小
                    if (isFileImg && file.size > $scope.ImgSize * 1024 * 1024) {
                        errMsgStr += file.name + "图片大小超过了" + $scope.ImgSize + "M";
                        file.isValidateError = true;
                        return
                    }
                    if (!isFileImg && file.size > $scope.FileSize * 1024 * 1024) {
                        errMsgStr += file.name + "文档大小超过了" + $scope.FileSize + "M";
                        file.isValidateError = true;
                        return;
                    }
                })

                if (!!errMsgStr) {
                    files = files.filter(function(item){ return !item.isValidateError });
                    ybWidget.ShowMessage(errMsgStr, MESG_TYPE.Error, {isHtml: true, isNotCenter: true})
                }

                var exceedNum = $scope.fileList.length + files.length - $scope.maxFileCount;
                if (exceedNum > 0) {
                    // 超过最大上传数量
                    files.splice(-exceedNum, exceedNum);
                }

                angular.forEach(files, function (item) {
                    (function(file){
                        var reader = new FileReader();
                        reader.onload = function (evt) {
                            $scope.$apply(function ($scope) {
                                $scope.fileList.push({ name: item.name, isImg: item.isImg, itemFile: file, base64: evt.target.result });
                            });
                        }
                        reader.readAsDataURL(file);
                    })(item)
                })
            };
            $scope.delFile = function (index) {
                $scope.fileList.splice(index, 1);
            };

            const uploadUrl = ybHttp.RequestUrl(settings.urlRoot, imgUploadUrlObj[settings.urlType]);

            var uploadFlag; // 图片批量上传正在进行中标志
            $scope.uploadFile = function () {
                if (uploadFlag) return;
                uploadFlag = true
                var uploadFileList = $scope.fileList.filter(function(item){return !item.hasUpload && (item.itemFile)}); // 需要上传的文件列表
                setTimeout(function() {
                    uploadFlag = false;
                }, uploadFileList.length * 600);

                angular.forEach(uploadFileList, function(file,index) {
                    setTimeout(function() {
                        Upload.upload({
                            url:  uploadUrl,
                            file: file.itemFile,
                        }).then(function(resp){
                            var resData = resp.data;
                            if (resData.code !== 0) {
                                ybWidget.ShowMessage(resData, MESG_TYPE.Error);
                            } else {
                                file.fileUrl = resData.value.imageUrl || resData.value;
                                file.fileUrlShow = getImgUrlShow(file.fileUrl);
                                file.filename = resData.value.filename;
                                if (file.isImg) {
                                  file.imgUrlShow = file.fileUrlShow;
                                }
                                file.hasUpload = true; // 标记上传
                            }
                        })
                    },600*index)
                })
            };

            $scope.isUploadDisabled = function () {
                return $scope.fileList.every(function(item){
                    return item.hasUpload
                })
            };

            function getImgUrlShow(val) {
                return imgRootObj[settings.urlType] + val;
            }

            $scope.downloadAttach =  function downloadAttach(file) {
                const a = document.createElement('a')
                a.href = file.fileUrlShow
                a.target = '_blank'
                a.download = file.filename // 下载后文件名
                a.style.display = 'none'
                document.body.appendChild(a)
                a.click() // 点击下载
                document.body.removeChild(a) // 下载完成移除元素
            }

            $scope.viewImage = function (item) {
              ybWidget.ViewImage({
                  FileUrl: item.imgUrlShow,
                  isRawUrl: true,
              })
            };

            $scope.ok = async function () {
                // 返回前提示有未上传的文件
                if ($scope.fileList.some(item => !item.hasUpload)) {
                  try {
                    await ybWidget.ShowMessage("存在未上传的文件，是否继续退出", MESG_TYPE.Ask, {
                      okName: "确定",
                      noName: "返回上传"
                    })
                    // 确定
                  } catch (error) {
                    // 返回上传分支
                    return
                  }
                }
                let fileContent = {};
                angular.extend(fileContent, { fileList: $scope.fileList });
                $modalInstance.close(fileContent);
            };
            $scope.cancel = function () {
                /* // 返回前提示有未上传的文件
                if ($scope.fileList.some(item => !item.hasUpload)) {
                  ybWidget.ShowToaster('warn', '存在未上传的文件');
                } */
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("ViewImageCtrl", ['$scope', '$modalInstance', 'settings', function ($scope, $modalInstance, settings) {
            $scope.file = settings;
            $scope.isRawUrl = settings.isRawUrl || false; // 是否直接显示原始url
            $scope.cancel = function () {
                $modalInstance.close();
            };

            let imgEle
            setTimeout(() => {
                imgEle = document.getElementById('transformImg');

                let startPosX = 0;
                let startPosY = 0;

                imgEle.addEventListener('dragstart', startDrag);
                imgEle.addEventListener('dragover', drag);

                function startDrag(event) {
                    startPosX = event.clientX - imgEle.offsetLeft;
                    startPosY = event.clientY - imgEle.offsetTop;
                }

                function drag(event) {
                    const offsetX = event.clientX - startPosX;
                    const offsetY = event.clientY - startPosY;
                    imgEle.style.left = offsetX + 'px';
                    imgEle.style.top = offsetY + 'px';
                }
            })

            let rotateAngle = 0
            $scope.handleRotate = function (val) {
                rotateAngle = rotateAngle + val

                imgEle.style.transform = imgEle.style.transform.replace(/^(rotate\(-?\d+deg\))?(.*)?$/g, "rotate(" + rotateAngle + "deg) $2")
            };

            let scaleVal = 1
            $scope.handleScale = function (val, isOrig) {
                scaleVal = scaleVal + val
                if (scaleVal <=0) {
                    scaleVal = 0.1
                }
                if (scaleVal >=20) {
                    scaleVal = 20
                }

                if (isOrig) {
                    scaleVal = 1
                }

                imgEle.style.transform = imgEle.style.transform.replace(/^(rotate\(-?\d+deg\))?(.*)?$/g, "$1 scale(" + scaleVal + ")")
            };
        }])

        .controller("AgentSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 5,
                pageSizeList: [5, 10],
                totalPages: 1,
                totalRows: 0
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = '/companyDealer/list';
                var param = {
                    filters: {
                        isPlatCompany: true
                    }
                };
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                param.filters = angular.extend(param.filters, $scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = Math.ceil(resp.value.total / param.pageSize);
                });
            }

            getListData();

            $scope.changePageItems = function () {
                $scope.pageInfo.curPage = 1;
                getListData();
            };
            $scope.pageChange = function () {
                getListData();
            };
            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.ok = function (index) {
                $modalInstance.close($scope.dataList[index]);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("WarehouseSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            isAllowI18n($scope);
            $scope.condition = {};
            $scope.checkSetstr=null;
            var checkSet=new Set();
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings.selectedId;
                var isNeedPermint = settings.needPermit;
                var isUnUsualOut = settings.isUnUsualOut;
                $scope.multy = settings.multy;
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = isNeedPermint ? '/warehouse/listByFilters/permit' : '/warehouse/listByFilters';
                if($scope.isTJ){
                    var reqUrl = "/warehouse/listByFilters/inventoryPermit";
                }
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                if (!!isUnUsualOut) {
                    reqUrl = '/warehouse/listByFilters/majorPermit';
                }
                var param = {
                    filters: angular.copy($scope.condition)
                };
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.clearWarehouse = function () {
                $scope.checkSetstr=null;
                checkSet.clear();
            };
            $scope.ok = function () {
                $modalInstance.close($scope.checkSetstr);
            };
            $scope.selectItem = function (item) {
                if($scope.multy){
                    checkSet.add(item.warehouseCode);
                    $scope.checkSetstr=Array.from(checkSet).join(",");
                }else{
                    $modalInstance.close(item);
                }

            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])
        .controller("WarehouseUsingSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            isAllowI18n($scope);
            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings.selectedId;
                var isNeedPermint = settings.needPermit;
                var isUnUsualOut = settings.isUnUsualOut;
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = isNeedPermint ? '/warehouse/listByFilters/permit' : '/warehouse/listByFilters';
                if($scope.isTJ){
                    var reqUrl = "/warehouse/listByFilters/inventoryPermit";
                }
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                if (!!isUnUsualOut) {
                    reqUrl = '/warehouse/listByFilters/majorPermit';
                }
                var param = {
                    filters: angular.copy($scope.condition)
                };
                param.filters.stopUsing = 0;
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])
        .controller("WarehouseUsingUserSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            isAllowI18n($scope);
            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings.selectedId;
                $scope.warehouseCode = settings.warehouseCode;
                $scope.forwardAllotPage = settings.forwardAllotPage;

            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = settings.reqUrl
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    filters: angular.copy($scope.condition)
                };
                param.filters.stopUsing = 0;
                param.filters.orgId = settings.param;
                if (!!settings&&settings.warehouseCode) {
                    param.filters.warehouseCode = settings.warehouseCode
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;

                if($scope.forwardAllotPage&&!settings.warehouseCode){
                   //直接不给做单据  dhg 需求
                    $scope.pageInfo.totalRows = 0;
                    $scope.pageInfo.totalPages = 0;
                    $scope.dataList = [];
                }else{
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        $scope.dataList = resp.value.pageInfo.list                    ;
                        $scope.dataList.forEach(item => {
                            item.companyName = item.description
                            item.supplierCode = item.warehouseCode
                        });
                        $scope.pageInfo.totalRows = resp.value.pageInfo.total;
                        $scope.pageInfo.totalPages = resp.value.pageInfo.pages;
                    });
                }

            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])
        .controller("DataSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', 'MESG_TYPE', function ($scope, $modalInstance, ybHttp, ybWidget, settings, MESG_TYPE) {
            isAllowI18n($scope);
            $scope.condition = {};
            $scope.markInfo = {
                allCheckedData: false,
            };
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0
            };
            $scope.dataList = [];
            $scope.currentType = {
                title: '',

                service: '',
                url: '',
                method: '',

                isNotFilterParam: false, // 为true时，接口所需 页面查询信息不放在filters字段上
                keyWords: [{label: '名称', field: 'name'}], // 组件内页面搜索条件输入框（最多支持两个）
                keyWordsParams: {}, // 组件内页面搜索条件输入框的默认值（key只能是keyWords字段中每项的field）
                otherParams: {}, // 调用该组件时外部传入的非页面可输入的 接口所需参数
                fields: [], // [{ name: 'xx', dataField: 'xx', width: "xx%" }]
                selectedKey: 'id', // 数据是否已被选择的判断字段
                isMultiSelect: false, // 是否支持多选
                isOnlyShow: false, // 是否仅展示信息(为true时，字段isMultiSelect将无效)
            };
            if (!!settings) {
                $scope.modalName = (settings.isOnlyShow?'':"选择") + settings.title;
                $scope.currentType = settings;

                angular.extend($scope.condition, $scope.currentType.keyWordsParams);
            }

            function getListData(curPage) {
                var service = $scope.currentType.service || 'device';
                var reqUrl = $scope.currentType.url;
                var reqMethod = $scope.currentType.method || 'Post';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }

                var param = {};
                if ($scope.currentType.isNotFilterParam) {
                    param = angular.copy(angular.extend($scope.condition, $scope.currentType.otherParams));
                } else {
                    param = {
                        filters: angular.copy(angular.extend($scope.condition, $scope.currentType.otherParams))
                    };
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp[reqMethod](service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (Array.isArray(resp.value)) {
                        $scope.dataList = resp.value;
                        $scope.pageInfo.totalRows = 1;
                        $scope.pageInfo.totalPages = 1;
                    } else {
                        $scope.dataList = resp.value.list;
                        $scope.pageInfo.totalRows = resp.value.total;
                        $scope.pageInfo.totalPages = resp.value.pages;
                    }
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };

            $scope.isEventStop = function () {
                if (!!settings.eventStop) {
                    window.event.stopPropagation()
                }
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
            };
            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    $scope.markInfo["allChecked" + type] = checkAll(list);
                }
            };
            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            };

            $scope.multiSelectConfirm = function () {
                let arr = $scope.dataList.filter(item => item.isChecked)
                if (arr.length < 1) {
                    ybWidget.ShowToaster('error', '请选择数据');
                    return
                }
                $modalInstance.close(arr);
            };
        }])

        .controller("CodeSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            isAllowI18n($scope);
            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = '/warehouse/listByFilters';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    filters: angular.copy($scope.condition)
                };
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("WarehouseASelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = '/warehouse/listNoBarcode';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {};
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                param.warehouseCode = $scope.condition.warehouseCode;
                param.description = $scope.condition.description;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("DatasShowCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            $scope.title = settings.title || '大厂库存';
            $scope.fields = settings.fields || [{ name: '库区', dataField: 'sapArea', width: '50%' }, { name: '库存', dataField: 'stock', width: '50%' }];
            $scope.dataList = settings.data || [];

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("StorageReportCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {

            isAllowI18n($scope);

            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = '/report/materialStorage';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    filters: {
                        materialsNo: settings.materialsNo
                    }
                };
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("IntentionDetailCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {

            isAllowI18n($scope);

            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = '/warehouseInventory/intentionDetail';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    filters: {
                        materialsNo: settings.materialsNo
                    }
                };
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
            $scope.tdClick = function (item) {
                ybWidget.SellIntentionDetail({id:item.id,type:item.billType});
            };
        }])

        .controller("DeliveryDetailCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {

            isAllowI18n($scope);

            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = '/warehouseInventory/deliveryDetail';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    filters: {
                        materialsNo: settings.materialsNo,
                        warehouseCode: settings.warehouseCode,
                        purchaseOrgName:settings.purchaseOrgName,
                    }
                };
                if (settings.billNo) {
                    param.filters.billNo = settings.billNo;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("DepotAreaSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {

            isAllowI18n($scope);

            $scope.condition = {};
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 10,
                pageSizeList: [10, 20, 30],
                totalPages: 1,
                totalRows: 0,
                hidePageJump: true
            };
            $scope.isWarehouse = false;
            $scope.dataList = [];
            if (!!settings.selectedId) {
                $scope.selectedId = settings.selectedId;
                $scope.isWarehouse = settings.isWarehouse;
            }

            function getListData(curPage) {
                var service = 'device';
                var reqUrl = '/warehouse/areaCodeListPage';
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    warehouseCode: settings.warehouseCode,
                    ...$scope.condition
                };
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                });
            }

            getListData();

            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.selectItem = function (item) {
                if($scope.isNJ&&settings.oppositeAreaCode){
                    if(settings.sapAreaCode&&!item.sapCode){
                        ybWidget.ShowMessage('请选择关联SAP编码的库区');
                        return;
                    }else if(!settings.sapAreaCode&&item.sapCode){
                        ybWidget.ShowMessage('请选择不关联SAP编码的库区');
                        return;
                    }
                }
                $modalInstance.close(item);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])
        .controller("SingleSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', '$document', 'MESG_TYPE', function ($scope, $modalInstance, ybHttp, ybWidget, settings, $document, MESG_TYPE) {

            isAllowI18n($scope);

            var typeMap = {

                servicer: {
                    server: 'auth',
                    url: '/profile/listByWorkspace',
                    keyWord: ['name'],
                    keyWordStr: ['服务人员名称'],
                    searchCondition: {
                        spaceId: settings.supplierOrgId
                    },
                    field: [{
                            name: '服务人员名称',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '登录名',
                            dataField: 'loginName',
                            width: "50%"
                        }
                    ]
                },

                customer: {
                    server: 'device',
                    url: '/dealerVehicle/notDeactivatedList',
                    keyWord: ['keyWord'],
                    keyWordStr: ['客户名称/整机编号'],
                    field: [{
                            name: '客户名称',
                            dataField: 'clientName',
                            width: "14%"
                        },
                        {
                            name: '客户编号',
                            dataField: 'clientCode',
                            width: "14%"
                        },
                        {
                            name: '整机编号',
                            dataField: 'carNo',
                            width: "14%"
                        },
                        {
                            name: '保养剩余额度',
                            dataField: 'maintenanceLaveAmount',
                            width: "18%"
                        },
                        {
                            name: '通用剩余额度',
                            dataField: 'universalLaveAmount',
                            width: "18%"
                        }
                    ]
                },
                customerJck: {
                    server: 'device',
                    url: '/dealerVehicle/jinchukouNotDeactivatedList',
                    keyWord: ['companyName'],
                    keyWordStr: ['客户名称'],
                    field: [{
                            name: '客户名称',
                            dataField: 'clientName',
                            width: "70%"
                        },
                    ]
                },
                notPackageMaterials: {
                    server: 'device',
                    url: '/boxup/notPackList',
                    keyWord: ['companyName'],
                    keyWordStr: ['零件编号'],
                    field: [{
                            name: '零件中文名',
                            dataField: 'materialsDes',
                            width: "20%"
                        },
                        {
                            name: '零件编号',
                            dataField: 'materialsNo',
                            width: "20%"
                        },
                        {
                            name: '数量',
                            dataField: 'qty',
                            width: "20%"
                        },
                    ]
                },
                dealer: {
                    server: 'device',
                    url: '/companyDealer/list',
                    keyWord: ['dealerCode', 'companyName'],
                    keyWordStr: ['客户编号', '客户名称'],
                    field: [{
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '客户编号',
                            dataField: 'dealerCode',
                            width: "40%"
                        }
                    ]
                },
                supplierName4Price: {
                    server: 'device',
                    url: '/companySupplier/listForPurchasePrice',
                    keyWord: ['supplierCode', 'companyName'],
                    keyWordStr: ['供货商代码', '供货商名称'],
                    field: [{
                            name: '供货商名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '供货商代码',
                            dataField: 'supplierCode',
                            width: "40%"
                        }
                    ]
                },
                commonDealer: {
                    server: 'device',
                    url: '/companyDealer/getRegularAgent',
                    keyWord: ['dealerCode', 'companyName'],
                    keyWordStr: ['客户编号', '客户名称'],
                    field: [{
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '客户编号',
                            dataField: 'dealerCode',
                            width: "40%"
                        }
                    ]
                },
                sharedDealer: {
                    server: 'device',
                    url: '/companyDealer/listByCurrentId',
                    keyWord: ['dealerCode', 'companyName'],
                    keyWordStr: ['客户编号', '客户名称'],
                    field: [{
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '客户编号',
                            dataField: 'dealerCode',
                            width: "40%"
                        }
                    ]
                },
                supplier: {
                    server: 'device',
                    url: '/companySupplier/list',
                    keyWord: ['companyName', 'supplierCode'],
                    keyWordStr: ['供货商名称', '供货商代码'],
                    field: [{
                            name: '供货商名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '供货商代码',
                            dataField: 'supplierCode',
                            width: "40%"
                        }
                    ]
                },
                carrier: {
                    server: 'device',
                    url: '/company/list',
                    keyWord: ['companyName'],
                    keyWordStr: ['公司名称'],
                    searchCondition: {
                        companyType: 3
                    },
                    field: [{
                            name: '公司名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '组织机构代码',
                            dataField: 'orgCode',
                            width: "40%"
                        }
                    ]
                },
                staff: {
                    server: 'auth',
                    url: '/profile/list',
                    keyWord: ['name'],
                    keyWordStr: ['员工姓名'],
                    searchCondition: {},
                    field: [{
                            name: '员工姓名',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '登录名',
                            dataField: 'loginName',
                            width: "50%"
                        }
                    ]
                },
                businessStaff: {
                    server: 'auth',
                    url: '/profile/listProfiles',
                    keyWord: ['name'],
                    keyWordStr: ['员工姓名'],
                    searchCondition: {},
                    field: [
                        {
                            name: '员工姓名',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '登录名',
                            dataField: 'loginName',
                            width: "50%"
                        }
                    ]
                },
                staffByWorkspace: {
                    server: 'auth',
                    url: '/profile/listByWorkspace',
                    keyWord: ['name', 'roleName'],
                    keyWordStr: ['调度员姓名', '角色'],
                    searchCondition: {
                        spaceId: settings.supplierOrgId,
                        fuzzyFlag: settings.fuzzyFlag
                    },
                    field: [{
                            name: '调度员姓名',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '登录名',
                            dataField: 'loginName',
                            width: "50%"
                        }
                    ]
                },
                agent: {
                    server: 'auth',
                    url: '/profile/listByWorkspace',
                    keyWord: ['name'],
                    keyWordStr: ['经办人姓名'],
                    searchCondition: {
                        spaceId: settings.supplierOrgId,
                    },
                    field: [{
                            name: '经办人姓名',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '登录名',
                            dataField: 'loginName',
                            width: "50%"
                        }
                    ]
                },
                dispatchStaff: {
                    server: 'auth',
                    url: '/profile/listByWorkspace',
                    keyWord: ['name', 'roleName'],
                    keyWordStr: ['调度人姓名', '角色'],
                    searchCondition: {
                        spaceId: settings.supplierOrgId
                    },
                    field: [{
                            name: '调度人姓名',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '登录名',
                            dataField: 'loginName',
                            width: "50%"
                        }
                    ]
                },
                auditStaff: {
                    server: 'auth',
                    url: '/profile/listByWorkspace',
                    keyWord: ['name'],
                    keyWordStr: ['审核人姓名'],
                    searchCondition: {
                        spaceId: settings.supplierOrgId
                    },
                    field: [{
                            name: '审核人姓名',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '登录名',
                            dataField: 'loginName',
                            width: "50%"
                        }
                    ]
                },
                custodian: {
                    server: 'auth',
                    url: '/profile/list',
                    keyWord: ['name'],
                    keyWordStr: ['保管员姓名'],
                    searchCondition: {},
                    field: [{
                            name: '保管员姓名',
                            dataField: 'name',
                            width: "35%"
                        },
                        {
                            name: '所属部门',
                            dataField: 'deptName',
                            width: "35%"
                        },
                        {
                            name: '手机号',
                            dataField: 'mobile',
                            width: "30%"
                        }
                    ]
                },
                purchaseGroup: {
                    server: 'device',
                    url: '/serviceBasicDataAgent/list',
                    keyWord: ['code'],
                    keyWordStr: ['采购组'],
                    searchCondition: {
                        pCode: "PURCHASEGROUP"
                    },
                    field: [{
                            name: '采购组',
                            dataField: 'code',
                            width: "50%"
                        },
                        {
                            name: '描述',
                            dataField: 'name',
                            width: "50%"
                        }
                    ]
                },
                line: {
                    server: 'device',
                    url: '/logisticsBasic/list',
                    keyWord: ['departureCity', 'destinationCity'],
                    keyWordStr: ['出发城市', '目的城市'],
                    searchCondition: {},
                    field: [{
                            name: '出发城市',
                            dataField: 'departureCity',
                            width: "33.3%"
                        },
                        {
                            name: '目的城市',
                            dataField: 'destinationCity',
                            width: "33.3%"
                        },
                        {
                            name: '承诺时间',
                            dataField: 'commitmentTime',
                            width: "33.3%"
                        }
                    ]
                },
                logistics: {
                    server: 'device',
                    url: '/deliveryReceipt/listAllActives',
                    keyWord: ['filters'],
                    keyWordStr: ['公司名称'],
                    field: [{
                            name: '公司名称',
                            dataField: 'expressName',
                            width: "60%"
                        },
                        {
                            name: '公司编号',
                            dataField: 'expressCode',
                            width: "40%"
                        }
                    ]
                },

                sapSel: {
                    server: 'device',
                    url: '/dataDictionary/searchListPage',
                    keyWord: ['code', 'name'],
                    keyWordStr: ['内部订单号', '内部订单号描述'],
                    field: [{
                            name: '内部订单号',
                            dataField: 'code',
                            width: "50%"
                        },
                        {
                            name: '内部订单号描述',
                            dataField: 'name',
                            width: "50%"
                        }
                    ]
                },

                agency: {
                    server: 'device',
                    url: '/serviceBasicDataAgent/list',
                    keyWord: ['name', ],
                    keyWordStr: ['名称'],
                    searchCondition: {
                        pCode: "Aency"
                    },
                    field: [
                        {
                            name: '名称',
                            dataField: 'name',
                            width: "50%"
                        },
                        {
                            name: '编码',
                            dataField: 'code',
                            width: "50%"
                        },
                    ]
                },
            };
            $scope.currentType = typeMap[settings.type];
            $scope.modalName = "选择" + settings.name;
            $scope.condition = {};
            if (settings.type === "staffByWorkspace") {
                $scope.condition.roleName = angular.isDefined(settings.defaultRoleName) ? settings.defaultRoleName : '销售';
                $scope.condition.spaceId = settings.supplierOrgId;
            }
            if (settings.type === "dispatchStaff" && settings.name === "调度人") {
                $scope.condition.roleName = "备件销售员";
                $scope.condition.spaceId = settings.supplierOrgId;
            }
            $scope.modalType = settings.type;
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 5,
                pageSizeList: [5, 10],
                totalPages: 1,
                totalRows: 0
            };
            $scope.dataList = [];
            $scope.checkBtnValid = false;
            if (angular.isDefined(settings.selectedItem)) {
                $scope.checkBtnValid = true;
                $scope.selectedRow = settings.selectedItem;
            }

            function getListData(curPage) {
                var service = $scope.currentType.server;
                var reqUrl = $scope.currentType.url;
                var param = {
                    filters: {}
                };
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                if (angular.isDefined($scope.currentType.searchCondition)) {
                    param.filters = angular.copy($scope.currentType.searchCondition);
                }
                if (settings.type === "dealer" && settings.supplierOrgId != null) {
                    $scope.condition.orgId = settings.supplierOrgId;
                }
                if (settings.type === "dealer" && settings.isPlatCompany != null) {
                    $scope.condition.isPlatCompany = settings.isPlatCompany;
                }
                if (settings.type === "line" && settings.carrierOrgId != null) {
                    $scope.condition.carrierOrgId = settings.carrierOrgId;
                }
                if (settings.type === "servicer") {
                    $scope.condition.roleName = settings.roleName;
                }
                if (settings.type === "supplier" && settings.soldOrgId != null) {
                    $scope.condition.orgId = settings.soldOrgId;
                    $scope.condition.isDirect = settings.isDirect;
                    if (settings.purchaseOrder) {
                        angular.forEach($scope.currentType.field, function (item) {
                            if (item.dataField === 'companyName') {
                                item.dataField = 'shortName';
                            }
                        });
                    }
                }

                if (settings.type === "supplier" && settings.isPlat == true) {
                    $scope.condition.isPlatCompany = 1;
                    $scope.condition.isDirect = 1;
                }

                if (settings.type === "sapSel") {
                    $scope.condition.parentCode = 'SBNBDD';
                    angular.forEach($scope.condition, function (val, key) {
                        if (!val) {
                            $scope.condition[key] = undefined;
                        }
                    })
                }

                param.filters = angular.extend(param.filters, $scope.condition);
                if (settings.type === "logistics") {
                    param.filters = $scope.condition.filters;
                }
                if (settings.type === "notPackageMaterials") {
                    param = {
                        deliveryReceiptNo : settings.deliveryReceiptNo
                    }
                    param.pageNum = $scope.pageInfo.curPage;
                    param.pageSize = $scope.pageInfo.pageSize;
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }

                        var resList = [];
                        var totalSize = 0;

                        if (settings.type === "sapSel") {
                            resList = resp.value.pageInfo.list;
                            totalSize = resp.value.pageInfo.total;
                        } else {
                            resList = resp.value;
                            // totalSize = resp.value.total;
                        }

                        $scope.dataList = resList;
                        $scope.pageInfo.totalRows = totalSize;
                        $scope.pageInfo.totalPages = Math.ceil(totalSize / param.pageSize);
                    });
                    return;
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    var resList = [];
                    var totalSize = 0;

                    if (settings.type === "sapSel") {
                        resList = resp.value.pageInfo.list;
                        totalSize = resp.value.pageInfo.total;
                    } 
                    // else if (settings.type === "agency") {
                    //     resList = resp.value;
                    //     totalSize = resp.value.total;
                    //     console.log(resList)
                    // }  
                    else {
                        resList = resp.value.list;
                        totalSize = resp.value.total;
                    }

                    $scope.dataList = resList;
                    $scope.pageInfo.totalRows = totalSize;
                    $scope.pageInfo.totalPages = Math.ceil(totalSize / param.pageSize);
                });
            }

            getListData();

            $scope.changePageItems = function () {
                $scope.pageInfo.curPage = 1;
                getListData();
            };
            $scope.pageChange = function () {
                getListData();
            };
            $scope.search = function (curPage) {
                getListData(curPage);
            };


            $scope.isEventStop = function () {
                if (!!settings.eventStop) {
                    window.event.stopPropagation()
                }
            };

            $scope.ok = function (index, event) {
                $modalInstance.close($scope.dataList[index]);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("DeliveryNoticeSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', 'MESG_TYPE', function ($scope, $modalInstance, ybHttp, ybWidget, settings, MESG_TYPE) {

            isAllowI18n($scope);

            $scope.currentType = {
                server: 'device',
                url: '/deliveryReceipt/outBillList',
                keyWord: ['keyWords'],
                keyWordStr: ['业务单号/客户名称'],
                searchCondition: {
                    billType: settings.billType,
                    planDate: settings.planDate
                },
                field: [{
                        name: '业务单号',
                        dataField: 'deliveryNo',
                        width: "35%"
                    },
                    {
                        name: '客户名称',
                        dataField: 'purchaseOrgName',
                        width: "35%"
                    },
                    {
                        name: '创建账号',
                        dataField: 'createName',
                        width: "30%"
                    }
                ]
            };
            $scope.modalName = settings.name;
            $scope.condition = {
                purchaseOrgId: settings.purchaseOrgId
            };
            $scope.deliveryBillIds = settings.deliveryBillIds;

            $scope.pageInfo = {
                curPage: 1,
                pageSize: 5,
                pageSizeList: [5, 10],
                totalPages: 1,
                totalRows: 0
            };
            $scope.dataList = [];
            $scope.checkBtnValid = false;
            if (angular.isDefined(settings.selectedItem)) {
                $scope.checkBtnValid = true;
                $scope.selectedRow = settings.selectedItem;
            }

            function getListData(curPage) {
                var service = $scope.currentType.server;
                var reqUrl = $scope.currentType.url;
                if (settings.threeDayPlan) {
                    reqUrl = '/deliveryReceipt/threeDayPlanBillList'
                }
                var param = {
                    filters: {}
                };
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                if (angular.isDefined($scope.currentType.searchCondition)) {
                    param.filters = angular.copy($scope.currentType.searchCondition);
                }
                param.filters = angular.extend(param.filters, $scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = Math.ceil(resp.value.total / param.pageSize);
                });
            }

            getListData();

            $scope.changePageItems = function () {
                $scope.pageInfo.curPage = 1;
                getListData();
            };
            $scope.pageChange = function () {
                getListData();
            };
            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.ok = function (index) {
                $modalInstance.close($scope.dataList[index]);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("PriceSchemeSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', 'MESG_TYPE', function ($scope, $modalInstance, ybHttp, ybWidget, settings, MESG_TYPE) {
            function getReqUrl() {
                switch (settings.schemeType) {
                    case 0:
                        // 查询价格方案列表--当前登录公司配给目标客户dealerOrgId的价格方案
                        if (!$scope.isBatchSetting) {
                            return '/marketingActivity/activityPriceList' // 单行
                        }
                        return '/marketingActivity/activityList' // 批量
                    case 1:
                        // 查询价格方案列表--目标供货商supplierOrgId配给当前登录公司的价格方案
                        if (!$scope.isBatchSetting) {
                            return '/marketingActivity/activityPriceList4Jck' // 单行
                        }
                        return '/marketingActivity/activityList4Jck' // 批量
                    default:
                        return ''
                }
            }

            $scope.selDisabled = settings.selectedDisabled;
            $scope.hideModeRate = settings.hideModeRateColumn;
            $scope.isBatchSetting = settings.isBatch;

            $scope.dataList = [];
            function getListData() {
                const apiInfo = settings?.apiObj || {};
                let { url: reqUrl, param } = apiInfo;
                if (!reqUrl) {
                    reqUrl = getReqUrl();
                }
                ybHttp.Get("device", reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value;
                });
            }

            getListData();

            $scope.ok = function (index) {
                $modalInstance.close($scope.dataList[index]);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("DepotSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {

            isAllowI18n($scope);

            $scope.areaList = [];
            $scope.placeList = [];
            var warehouseCode = settings.warehouseCode;
            var areaSelected = "";
            var depotInfo = {
                warehouseCode: warehouseCode,
                areaCode: "",
                locationCode: ""
            };

            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 20,
                curPage: 1,
                hidePages: true,
                hidePageSize: true,
                hidePageJump: true
            };

            function getAreaList() {
                var service = "device";
                var reqUrl = settings.reqUrl || '/warehouse/findAreaCodeList';
                var param = {};
                param.warehouseCode = warehouseCode;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message);
                        return;
                    }
                    $scope.areaList = resp.value.list;
                    if ($scope.areaList.length > 0) {
                        $scope.areaList[0].selected = true;
                        areaSelected = $scope.areaList[0].id;
                        depotInfo.areaCode = $scope.areaList[0].areaCode;
                        getPlaceList(1);
                    }
                });
            }

            $scope.getPlace = function (list, index) {
                areaSelected = $scope.areaList[index].id;
                depotInfo.areaCode = $scope.areaList[index].areaCode;
                depotInfo.locationCode = "";
                setSelectRow(list, index);
                getPlaceList(1);
            };

            function getPlaceList (curPage) {
                var service = "device";
                var reqUrl = "/warehouse/listLocations";
                var param = {};
                param.areaId = areaSelected;
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;

                param.location = $scope.locationSearchKey;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.placeList = resp.value.list;
                });
            };

            $scope.searchPlace = function () {
                getPlaceList();
            };

            $scope.selPlace = function (list, index) {
                setSelectRow(list, index);
                depotInfo.locationCode = $scope.placeList[index].locationCode;
            };

            function setSelectRow(list, index) {
                angular.forEach(list, function (item) {
                    item.selected = false;
                });
                list[index].selected = true;
            }

            getAreaList(areaSelected);

            $scope.ok = function () {
                $modalInstance.close(depotInfo);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])
        .controller("SelectDeliveryAddressCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            // settings.dealerOrgId，存在表示搜索代理的地址，false搜索自己的地址
            $scope.condition = {
                receiverName: settings.deliveryName || '',
                clientReceiveInfo: settings.clientReceiveInfo
            };
            $scope.pageInfo = {
                curPage: 1,
                pageSize: 5,
                pageSizeList: [5, 10],
                totalPages: 1,
                totalRows: 0
            };
            $scope.dataList = [];
            if (!!settings) {
                $scope.selectedId = settings
            }

            function getListData() {
                var service = 'device';
                var reqUrl, param;
                if ($scope.condition.clientReceiveInfo) {
                    reqUrl = '/companyDealer/listSelfReceiversBySupplier';
                    param = {};
                    param.supplierPlatOrgId = settings.supplierOrgId;
                    param.clientOrgId = settings.clientOrgId;
                    param = angular.extend(param, $scope.condition);
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        $scope.dataList = resp.value;
                        angular.forEach($scope.dataList, function (item) {
                            item.isChecked = false;
                            item.receiverAddress = item.address;
                            item.receiverTel = item.phone;
                        });
                    });
                } else {
                    reqUrl = '/companyAddress/receiverMatching';
                    param = {
                        dealerOrgId: settings.dealerOrgId ? settings.dealerOrgId : ''
                    };
                    param = angular.extend(param, $scope.condition);
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        $scope.dataList = resp.value;
                    });
                }
            }

            getListData();

            $scope.search = function () {
                getListData();
            };
            $scope.ok = function (index) {
                $modalInstance.close($scope.dataList[index]);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("ScissorPictureCtrl", ['$scope', '$modalInstance', 'settings', function ($scope, $modalInstance, settings) {
            $scope.myImage = settings.curFile.base64;
            $scope.myCroppedImage = '';

            //将base64转换为文件
            function dataURLtoFile(dataurl, filename) {
                var arr = dataurl.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, {
                    type: mime
                });
            }
            $scope.ok = function () {
                settings.curFile.cropBase64 = $scope.myCroppedImage;
                settings.curFile.cropImg = dataURLtoFile($scope.myCroppedImage, settings.curFile.img.name);
                $modalInstance.close(settings);
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("LogisticsWaybillDetailCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {
            function getData() {
                var service = 'device';
                var reqUrl = '/logisticWaybillFee/viewWayBillInfo';
                var param = {
                    wayBillId: settings.wayBillId
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo = resp.value;
                });
            }

            getData();

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("SellIntentionDetailCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', function ($scope, $modalInstance, ybHttp, ybWidget, settings) {

            getData();

            function getData() {

                var service = 'device';
                var reqUrl = '/saleIntention/item';
                var param = {
                    id: settings.id
                };
                $scope.type = settings.type;
                if($scope.type === "XGSB")
                {
                    var service = 'device';
                    var reqUrl = '/threeGuaranteesPur/item';
                }
                if($scope.type === "XGQY")
                {
                     service = 'device';
                     reqUrl = '/forwardAllotApply/detail';
                }

                $scope.detailInfo ={};
                $scope.detailList ={};
                ybHttp.Get(service, reqUrl, param).then(function (resp) {

                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, "获取数据失败");
                        return;
                    }
                    $scope.orderObj= resp.value;
                    $scope.detailInfo= resp.value.headerInfo;

                    if($scope.type === "XGSB"){
                        $scope.detailList= resp.value.detailList;
                    }
                    else
                    {
                        $scope.detailList= resp.value.materialList;
                    }

                });
            }



            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };

            $scope.viewTbConf = {
                scrollWidth: 200,
                tableCol: [
                    {
                        type: "",
                        name: "行号",
                        dataField: "lineNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 120,
                        dataField: "materialsNo"
                    },
                    {
                        name: "原零件号",
                        width: 120,
                        dataField: "originalMaterialsNo"
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes"
                    },
                    {
                        name: "零件分类",
                        width: 100,
                        dataField: "sortName"
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit"
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price"
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalPrice"
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName"
                    },
                    {
                        name: "调整后数量",
                        width: 100,
                        dataField: "amountAfterAdjust"
                    },
                    {
                        name: "调整后单价",
                        width: 100,
                        dataField: "unitPriceAfterAdjust"
                    },
                    {
                        name: "调整后总价",
                        width: 100,
                        dataField: "totalPriceAfterAdjust"
                    },
                    {
                        name: "标准价",
                        width: 100,
                        dataField: "standardPrice",
                        hidden: !$scope.isJCH, // 仅限基础
                    },
                    {
                        name: "外销单价",
                        width: 100,
                        dataField: "exportPrice",
                        hidden: !$scope.isJCHK, // 仅限进出口
                    },
                    {
                        name: "外销金额",
                        width: 100,
                        dataField: "totalExportPrice",
                        hidden: !$scope.isJCHK, // 仅限进出口
                    },
                    {
                        name: "创建发货数量",
                        width: 120,
                        dataField: "informedAmount"
                    },
                    {
                        name: "实际出库数量",
                        width: 120,
                        dataField: "inventoryOutAmount"
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum"
                    },
                    {
                        name: "意向占用",
                        width: 120,
                        dataField: "intentionNum"
                    },
                    {
                        name: "发货占用",
                        width: 120,
                        dataField: "deliveryNum"
                    },
                    {
                        name: "发货时间",
                        width: 150,
                        dataField: "requestDeliveryDateShow"
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark"
                    }
                ]
            };

            $scope.materielTableConfig = {
                fixedWidth: 340,
                scrollWidth: 870,
                tableCol: [
                    {
                        name: "序号",
                        width: 60,
                        dataField: "rowNo",
                        isShow: false,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "零件编号",
                        width: 100,
                        dataField: "materialsNo",
                        isShow: true,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 180,
                        dataField: "materialsDesc",
                        isShow: true,
                        isFixed: true,
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "领料单号",
                        width: 100,
                        dataField: "transferBillNo",
                        isShow: false
                    },
                    {
                        name: "领料单状态",
                        width: 100,
                        dataField: "transferStatusName",
                        isShow: false
                    },
                    {
                        name: "参考单价(￥)",
                        width: 120,
                        dataField: "price",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "purchaseQty",
                        isShow: true,
                        needInput: true
                    },
                    {
                        name: "服务库存",
                        width: 100,
                        dataField: "fwAmount",
                        isShow: false
                    },
                    {
                        name: "服务非条码库存",
                        width: 100,
                        dataField: "fwFtmAmount",
                        isShow: false
                    },
                    {
                        name: "备件库存",
                        width: 100,
                        dataField: "bjAmount",
                        clickFn: "selectWarehouse",
                        isShow: false
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        dataField: "dcAmount",
                        clickFn: "selectWarehouse",
                        isShow: false
                    },
                    {
                        name: "领料仓库",
                        width: 100,
                        dataField: "warehouseCode",
                        isShow: false
                    },
                    {
                        name: "领料库区",
                        width: 100,
                        dataField: "areaCode",
                        isShow: false
                    },
                    {
                        name: "调拨数量",
                        width: 100,
                        dataField: "transferAmount",
                        isShow: false,
                        needInput: true
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "amount",
                        isShow: true,
                        clickFn: "alterReport",
                        needInput: false
                    },
                    {
                        name: "已建出库数量",
                        width: 100,
                        dataField: "deliveryQty",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "实际出库数量",
                        width: 100,
                        dataField: "realQty",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "合计(￥)",
                        width: 100,
                        dataField: "totalPrice",
                        isShow: true,
                        needInput: false
                    },
                    {
                        name: "供货商名称",
                        width: 100,
                        dataField: "supplierName",
                        isShow: false
                    },
                    {
                        name: "生产批次号",
                        width: 100,
                        dataField: "batchNo",
                        isShow: false
                    },
                    {
                        name: "SAP预留号",
                        width: 120,
                        dataField: "reservedOrder",
                        isShow: false
                    },
                ]
            };



            $scope.viewXGQYTbConf ={
                fixedWidth: 340,
                scrollWidth: 870,
                tableCol:[
                    {
                        name: "零件编号",
                        width: 100,
                        dataField: "materialNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 140,
                        dataField: "materialName",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "applyQty",
                        needInput: true,
                        needRequired: true
                    },
                    {
                        name: "已建区域调拨单数量",
                        width: 150,
                        dataField: "createQty",
                        needInput: false
                    },
                    {
                        name: "备注",
                        width: 140,
                        dataField: "remark",
                        needInput: false
                    }
                ]
            }
        }])

        .controller("ShowDatePickerCtrl", ['$scope', '$modalInstance', 'setting', function ($scope, $modalInstance, setting) {
            $scope.modalName = setting && setting.name || '日期';

            $scope.myDate = "";

            $scope.ok = function (index) {
                $modalInstance.close($scope.myDate);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("AutoAddHandoverBillCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'MESG_TYPE', function ($scope, $modalInstance, ybHttp, ybWidget, MESG_TYPE) {
            $scope.dataInfo = {
                billType: 'XGFT'
            };

            $scope.billTypeList = [
                {
                    code: "XGFT",
                    name: "发货通知单"
                },
                {
                    code: "XGSC",
                    name: "三包出库单"
                },
                {
                    code: "XGQD",
                    name: "区域调拨单"
                },
                {
                    code: "XGFC",
                    name: "其它出库单"
                },
                {
                    code: "XSCK",
                    name: "销售赠送出库"
                }
            ];

            $scope.warehouseList = [
                {
                    code: null,
                    name: "请选择"
                }
            ];

            function getWarehouses() {
                var service = "device";
                var reqUrl = "/warehouse/listWarehouses";
                var param = {
                    pageNum: 1,
                    pageSize: 100
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var flag = false;
                    angular.forEach(resp.value.list, function (item) {
                        $scope.warehouseList.push({
                            code: item.warehouseCode,
                            name: item.warehouseCode
                        });
                        if ("WJBJ" === item.warehouseCode) {
                            flag = true;
                        }
                    });

                    if (flag) {
                        $scope.dataInfo.warehouseCode = "WJBJ";
                    }
                });
            }

            $scope.selectDealer = function () {
                ybWidget.DataSelector({
                    title: '客户',
                    url: '/deliveryReceipt/dealerWhenAutoCreate',
                    isNotFilterParam: false,
                    keyWords: [{label: '客户名称', field: 'companyName'}],
                    fields: [
                        {
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "50%"
                        },
                        {
                            name: '客户编码',
                            dataField: 'dealerOrgId',
                            width: "50%"
                        }
                    ]
                }).then(function (data) {
                    $scope.dataInfo.dealerOrgName = data.companyName;
                    $scope.dataInfo.dealerOrgId = data.dealerOrgId;
                })
            };

            $scope.ok = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.dataInfo.billType!='XGFT') {
                    $scope.dataInfo.warehouseCode = undefined;
                }

                ybHttp.Post('device', '/deliveryReceipt/batchAutoCreate', $scope.dataInfo).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $modalInstance.close();
                })
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };

            getWarehouses();
        }])

        .controller("GuaranteesFeeSettleSelectorCtrl", ['$scope', '$modalInstance', 'ybHttp', 'ybWidget', 'settings', 'MESG_TYPE', function ($scope, $modalInstance, ybHttp, ybWidget, settings, MESG_TYPE) {

            isAllowI18n($scope);

            $scope.currentType = {
                server: 'device',
                url: '/threeGuaFeeSettlement/salesOuts',
                keyWord: ['salesOutBillNo'],
                keyWordStr: ['销售出库单号'],
                searchCondition: {
                    salesOutBillNo: settings.salesOutBillNo,
                },
                field: [{
                    name: 'CRM单据号',
                    dataField: 'crmOrder',
                    width: "25%"
                },
                    {
                        name: '销售出库单号',
                        dataField: 'salesOutBillNo',
                        width: "30%"
                    },
                    {
                        name: '收货人',
                        dataField: 'consignee',
                        width: "20%"
                    },
                    {
                        name: '客户名称',
                        dataField: 'settlementOrgName',
                        width: "20%"
                    }
                ]
            };
            $scope.modalName = settings.name;
            $scope.condition = {
                purchaseOrgId: settings.purchaseOrgId
            };
            $scope.selectedList = settings.selectedList&& settings.selectedList.length>0?
                settings.selectedList.map(item => {
                    return item.salesOutBillNo
                }) :[];

            $scope.pageInfo = {
                curPage: 1,
                pageSize: 5,
                pageSizeList: [5, 10],
                totalPages: 1,
                totalRows: 0
            };
            $scope.dataList = [];

            function getListData(curPage) {
                var service = $scope.currentType.server;
                var reqUrl = $scope.currentType.url;
                var param = {
                    filters: {}
                };
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.pageSize = $scope.pageInfo.pageSize;
                if (angular.isDefined($scope.currentType.searchCondition)) {
                    param.filters = angular.copy($scope.currentType.searchCondition);
                }
                param.filters = angular.extend(param.filters, $scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.dataList = resp.value.list;
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = Math.ceil(resp.value.total / param.pageSize);
                });
            }

            getListData();

            $scope.changePageItems = function () {
                $scope.pageInfo.curPage = 1;
                getListData();
            };
            $scope.pageChange = function () {
                getListData();
            };
            $scope.search = function (curPage) {
                getListData(curPage);
            };
            $scope.ok = function (index) {
                $modalInstance.close($scope.dataList[index]);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }])

        .controller("SelGaodeMapCtrl", [
            "$scope",
            "$modalInstance",
            "settings",
            function ($scope, $modalInstance, settings) {
              $scope.mapOptions = {
                lng: settings.lng,
                lat: settings.lat,
                address: settings.address,
              };
      
              $scope.addressDetail = ""; // 详细地址
              $scope.divisionArr = ""; // 省市区
              $scope.positionArr = ""; // 经纬度
      
              $scope.selAddress = function (a, b, c) {
                $scope.addressDetail = a;
                $scope.divisionArr = b;
                $scope.positionArr = c;
              };
      
              $scope.ok = function () {
                $modalInstance.close({
                  a: $scope.addressDetail,
                  b: $scope.divisionArr,
                  c: $scope.positionArr,
                });
              };
      
              $scope.cancel = function () {
                $modalInstance.dismiss("cancel");
              };
            },
        ])
      
        .controller("ShowGaodeMapRouteCtrl", [
            "$scope",
            "$modalInstance",
            "settings",
            function ($scope, $modalInstance, settings) {
              $scope.mapOptions = {
                startLngLatArr: [settings.startLng, settings.startLat],
                endLngLatArr: [settings.endLng, settings.endLat],
              };
      
              $scope.cancel = function () {
                $modalInstance.dismiss("cancel");
              };
            },
        ])
        .controller("RepairFormCtrl", [
            "$scope",
            "$modalInstance",
            "settings",
            "ybHttp",
            "ybWidget",
            "MESG_TYPE",
            function ($scope, $modalInstance, settings, ybHttp, ybWidget, MESG_TYPE) {
              $scope.detailInfo = angular.copy(settings);
              $scope.dataInfo = {};
      
              // 转移营销部--特机登录
              if (settings.type == 1) {
                ybHttp
                  .Post("sync", "/ynMarketingCenter/list", {
                    pageNum: 1,
                    pageSize: 500,
                  })
                  .then(function (res) {
                    if (res.code !== 0) {
                      ybWidget.ShowMessage(res.message, MESG_TYPE.Error);
                      return;
                    }
                    $scope.marketingCenters = res.value.list || [];
                  });
              }
              // 分单--特机登录
              if (settings.type == 2) {
                const param = {
                  searchCenterCode: $scope.detailInfo.marketingCenterCode,
                  dealerTypeList: [5],
                };
                getCompanyDealers(param).then(function (data) {
                  $scope.companyFWZ1Dealers = data.list || []; // 一级服务站列表
      
                  if (settings.level1ReserveStationId) { // 一级服务站默认取 预约服务站(如果有)
                    $scope.dataInfo.newFWZ1 = $scope.companyFWZ1Dealers.find((c) => c.platOrgId == settings.level1ReserveStationId);
                    $scope.handleFWZ1Change(); //模拟页面一级服务站发生变化
                  }
                });
              }
              // 分单--一级服务站登录
              if (settings.type == 3) {
                const param = {
                  orgId: $scope.detailInfo.level1ServiceStationId, // 一级服务站的orgId
                  dealerTypeList: [5, 50],
                  applyStatus: 5,
                };
                getCompanyDealers(param).then(function (data) {
                  $scope.companyFWZ2Dealers = data.list || [];
                });
              }
              // 派工--一级服务站登录/二级服务站登录
              if (settings.type == 4 || settings.type == 5) {
                ybHttp
                  .Post("mt", "/technician/list", { pageNum: 1, pageSize: 500 })
                  .then(function (res) {
                    if (res.code !== 0) {
                      ybWidget.ShowMessage(res.message, MESG_TYPE.Error);
                      return;
                    }
                    const techDatas = res.value.list || [];
                    techDatas.forEach(
                      (t) => (t.cnameTel = `${t.cname} (${t.mobilePhone})`)
                    );
                    $scope.technicians = techDatas;
                  });
              }
      
              // 已经传输crp的单子 修改整车编码
              if (settings.type == 6) {
                $scope.dataInfo.engineNo = $scope.detailInfo.engineNo;
              }
      
              // 一级服务站变化的时候，查询二级服务站列表---------分单--特机登录时
              $scope.handleFWZ1Change = function () {
                $scope.dataInfo.newFWZ2 = {};
                $scope.companyFWZ2Dealers = [];
                if (!$scope.dataInfo.newFWZ1 || !$scope.dataInfo.newFWZ1.platOrgId) return;
                const param = {
                  orgId: $scope.dataInfo.newFWZ1.platOrgId, // 一级服务站的orgId
                  dealerTypeList: [5, 50],
                  applyStatus: 5,
                };
                getCompanyDealers(param).then(function (data) {
                  $scope.companyFWZ2Dealers = data.list || [];
                });
              };
      
              // 查询业务伙伴【一级服务站 or 二级服务站】
              function getCompanyDealers(obj) {
                var param = {
                  pageNum: 1,
                  pageSize: 500,
                  filters: obj,
                };
                return ybHttp
                  .Post("device", "/companyDealer/listTejiWeixiu", param)
                  .then(function (resp) {
                    if (resp.code !== 0) {
                      ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                      return;
                    }
                    return resp.value || {};
                  });
              }
      
              $scope.ok = function (isValid) {
                if (!isValid) {
                  $scope.submitted = true;
                  return;
                }
                let reqUrl = "";
                let param = {};
                // 转移营销部--特机登录
                if (settings.type == 1) {
                  reqUrl = "/repairForm/transfer";
                  param = {
                    id: $scope.detailInfo.id,
                    marketingCenterCode: $scope.dataInfo.newMC.dm,
                    marketingCenterName: $scope.dataInfo.newMC.mc,
                  };
                }
                // 分单--特机登录
                if (settings.type == 2) {
                  reqUrl = "/repairForm/distribute";
                  param = {
                    id: $scope.detailInfo.id,
                    level1ServiceStation: $scope.dataInfo.newFWZ1.companyName,
                    level1ServiceStationId: $scope.dataInfo.newFWZ1.platOrgId,
                    level2ServiceStation: $scope.dataInfo.newFWZ2 ? $scope.dataInfo.newFWZ2.companyName : "",
                    level2ServiceStationId: $scope.dataInfo.newFWZ2 ? $scope.dataInfo.newFWZ2.platOrgId : "",
                    distributeRemark: $scope.dataInfo.remark,
                  };
                }
                // 分单--一级服务站登录
                if (settings.type == 3) {
                  reqUrl = "/repairForm/distribute";
                  param = {
                    id: $scope.detailInfo.id,
                    level2ServiceStation: $scope.dataInfo.newFWZ2.companyName,
                    level2ServiceStationId: $scope.dataInfo.newFWZ2.platOrgId,
                    distributeRemark: $scope.dataInfo.remark,
                  };
                }
                // 派工--一级服务站登录/二级服务站登录
                if (settings.type == 4 || settings.type == 5) {
                  var startLngLat = [settings.stationLng, settings.stationLat];
                  var endLngLat = [settings.lng, settings.lat];
                  if (!settings.lng || JSON.stringify(startLngLat) == JSON.stringify(endLngLat)) { // 没有车辆位置 或者 站内报修
                    handDispatch(0);
                  } else {
                    var driving = new AMap.Driving({
                        policy: 2, // 距离最短策略
                    });
                    driving.search(startLngLat, endLngLat, function (status, result) {
                      handDispatch(result.routes[0].distance);
                    });
                  }
                  return;
                }
                // 已经传输ERP的单子，修改整车编码
                if (settings.type == 6) {
                  if ($scope.dataInfo.engineNo == $scope.detailInfo.engineNo) {
                    $modalInstance.close(true);
                    return;
                  }
                  reqUrl = "/repairForm/updateAfterCrmEdit";
                  param = {
                    id: $scope.detailInfo.id,
                    engineNo: $scope.dataInfo.engineNo,
                  };
                }
      
                ybHttp.Post("mt", reqUrl, param).then(function (res) {
                  if (res.code !== 0) {
                    ybWidget.ShowMessage(res.message, MESG_TYPE.Error);
                    return;
                  }
                  ybWidget.ShowToaster("success", "操作成功");
                  $modalInstance.close();
                });
              };
      
              function handDispatch(expectDistance) {
                const param = {
                  id: $scope.detailInfo.id,
                  technicianId: $scope.dataInfo.tech.id,
                  technicianName: $scope.dataInfo.tech.cname,
                  expectsMileage: expectDistance, // 服务站--车辆距离
                };
                ybHttp.Post("mt", "/repairForm/dispatch", param).then(function (res) {
                  if (res.code !== 0) {
                    ybWidget.ShowMessage(res.message, MESG_TYPE.Error);
                    return;
                  }
                  ybWidget.ShowToaster("success", "操作成功");
                  $modalInstance.close();
                });
              }
      
              $scope.cancel = function () {
                $modalInstance.dismiss("cancel");
              };
            },
        ])
        ;
})(window, window.angular);
